What is the String.lines() method in Java?

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

Example

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:

  • An empty string contains 0 lines.
  • A line can be:
    • zero or more characters followed by a line terminator (e.g., "test\n", "\n").
    • one or more characters followed by end of string (e.g., "test", "a").
  • The stream returned from the lines method is in the same string order as the string where we called the lines method.
  • The line doesn’t include the line terminator.

Free Resources