Java 11 introduced multiple enhancements to String.
- String.lines() − Return the stream of lines of multi-line string.
- String.strip() − Removes the leading and trailing whitespaces.
- String.stripLeading() − Removes the leading whitespaces.
- String.stripTrailing() − Removes the trailing whitespaces.
- String.repeat(int) − Repeats a string given number of times. Returns the concatenated string.
- String.isBlank() − Checks if a string is empty or have white spaces only.
Consider the following program−
Java11String.java
import java.util.ArrayList;
import java.util.List;
public class Java11String {
public static void main(String[] args) {
// 1. Stream of lines of multi-line string
String str = "This\nis\na\nmultiline\ntext\nstring.";
List<String> lines = new ArrayList<>();
str.lines().forEach(line -> lines.add(line));
lines.forEach(line -> System.out.println(line));
String txt = " xyz ";
// 2. Removes the leading and trailing whitespaces
System.out.println(txt.strip());
// 3. Removes the leading whitespaces
System.out.println(txt.stripLeading());
// 4. Removes the trailing whitespaces
System.out.println(txt.stripTrailing());
// 5. Repeats a string given number of times
System.out.println(txt.repeat(2));
// 6. Checks if a string is empty or have white spaces only
System.out.println(txt.isBlank()); // false
System.out.println("".isBlank()); // true
System.out.println(" ".isBlank()); // true
}
}
Output
This
is
a
multiline
text
string.
xyz
xyz
xyz
xyz xyz
false
true
true