String.lines() for line splitting
Use String.lines() to split text into a stream of lines without regex overhead.
Code Comparison
✕ Java 8
String text = "one\ntwo\nthree";
String[] lines = text.split("\n");
for (String line : lines) {
System.out.println(line);
}
✓ Java 11+
String text = "one\ntwo\nthree"; text.lines().forEach(System.out::println);
Why the modern way wins
Lazy streaming
Lines are produced on demand, not all at once like split().
Universal line endings
Handles \n, \r, and \r\n automatically without regex.
Stream integration
Returns a Stream for direct use with filter, map, collect.
Old Approach
split("\\n")
Modern Approach
lines()
Since JDK
11
Difficulty
beginner
JDK Support
String.lines() for line splitting
Available
Available since JDK 11 (September 2018).
How it works
String.lines() returns a Stream<String> of lines split by \n, \r, or \r\n. It is lazier and more efficient than split(), avoids regex compilation, and integrates naturally with the Stream API for further processing.
Related Documentation