In Java, lines() returns a Stream<String> with one element per line of the string. A line ends at \n, \r, or \r\n, and the terminators are not included in the elements.
Because it is a stream, you can filter, map, and count lines directly. It also handles every line-ending style, which a hand-written split("\n") does not, and it does not create an empty last line for text that ends with a newline.
lines() is an instance method of java.lang.String, added in Java 11. Call it on a string, as in text.lines(); calling it on a null reference throws NullPointerException. It only reads the text; the string itself is never changed. Requires Java 11 or newer.
Syntax
Call it with no arguments and process the stream.
java
long count = text.lines().count();
text.lines().filter(line -> !line.isBlank()).forEach(System.out::println);
Call
What it does
"a\nb".lines().count()
2.
"a\r\nb\rc".lines().count()
3.
"".lines().count()
0.
A line terminator at the very end does not start a new line: "a\nb\n" has 2 lines. Empty lines in the middle are kept as empty strings.
Library declarations
java
public Stream<String> lines();
Parameters
Parameter
Description
None
lines() takes no parameters.
Return Value
Return Value
Description
Stream<String>
The lines in order, without line terminators.
Java Examples
Example 1 — Read Lines with Mixed Line Endings
Unix, Windows, and old Mac terminators in a single string.
java
public class LinesMixed {
public static void main(String[] args) {
String text = "first\nsecond\r\nthird\rfourth";
System.out.println("length: " + text.length());
text.lines().forEach(line -> System.out.println("[" + line + "] " + line.length()));
}
}