Java 11 adds a new method called lines to the String class that returns a Stream of lines extracted from a string.
The string is separated for every:
Line feed character - \n
Carriage return character - \r
Carriage return character followed immediately by a line feed character - \r\n
import java.util.stream.Stream;public class Main{public static void main(String[] args){String str = "Line 1 \n Line 2 \r Line 3 \r\n Line 4";Stream<String> lines = str.lines();lines.forEach(line -> {System.out.println(line);});}}
In the above code, we have a string with multiple lines. We separate each line with the String.lines()
method, which returns a Stream of lines. We then loop through the stream and print the line.
Points to note:
0
lines."test\n", "\n"
)."test", "a"
).lines
method is in the same string order as the string where we called the lines method.