Java 8+ String Enhancements: New Methods and Best Practices

Java 8: Joining Strings and Streams

1. String.join(): Concatenate Collections

Combine elements with a delimiter effortlessly:

List<String> langs = List.of("Java", "Python", "C++");  
String csv = String.join(", ", langs);  // "Java, Python, C++"  

2. chars() & codePoints(): Stream Characters

Process characters via streams (e.g., count vowels):

long vowels = "Java".chars()  
                   .filter(c -> "aeiou".indexOf(Character.toLowerCase(c)) != -1)  
                   .count();  // 2  
  • chars(): Returns IntStream of UTF-16 code units.
  • codePoints(): Handles Unicode code points (supports emojis, etc.).

Java 11: Quality-of-Life Improvements

1. isBlank() vs isEmpty()

  • isEmpty(): Checks if length is 0.
  • isBlank(): Checks if empty or contains only whitespace.
"  ".isEmpty();   // false  
"  ".isBlank();   // true  

2. lines(): Split Lines Properly

Split multi-line strings while handling \n\r, and \r\n:

String text = "Line1\nLine2\r\nLine3";  
List<String> lines = text.lines().toList();  // ["Line1", "Line2", "Line3"]  

3. strip()stripLeading()stripTrailing()

Unicode-aware whitespace removal (better than trim()):

String s = "\u2000  Hello  \u2000";  
s.strip();          // "Hello"  
s.stripLeading();   // "Hello  \u2000"  
s.stripTrailing();  // "\u2000  Hello"  

trim() vs strip():

  • trim() removes only ASCII whitespace (≤ U+0020).
  • strip() removes all Unicode whitespace (e.g., \u2000).

4. repeat(int count): String Multiplication

Repeat a string count times:

"Java ".repeat(3);  // "Java Java Java "  

Java 15: Text Blocks (Standardized)

Multi-line strings with """ syntax (covered in Java Special Characters):

String json = """  
              { 
                "name": "Alice",  
                "age": 30  
              }  
              """;  

Best Practices

  1. Replace Legacy Code:
    • Use isBlank() instead of trim().isEmpty().
    • Prefer lines() over split("\\r?\\n").
  2. Avoid repeat() for Large Counts: Can cause memory issues (test with count ≤ Integer.MAX_VALUE).
  3. Use strip() for Modern Apps: Ensure Unicode compatibility.

Common Mistakes

❌ Misusing chars() for Unicode:

"🚀".chars().count();  // 2 (surrogate pair)  
"🚀".codePoints().count();  // 1 (correct)  

❌ Assuming isBlank() == isEmpty():

if (input.isBlank() && !input.isEmpty()) {  
    // Handle whitespace-only input  
}  

FAQ

Are these methods available in Android?

Yes, if using Android API 26+ (Java 8) or API 30+ (Java 11).

How to check for blank but non-null strings?

Combine with Optional:

Optional.ofNullable(str).filter(s -> !s.isBlank()).orElse(“default”);

What’s the performance impact of lines()?

Similar to splitting manually but cleaner and more maintainable.

Sharing Is Caring:
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments