String.lines() for line splitting
Home / Strings / String.lines() for line splitting
Code Comparison
String text = "one\ntwo\nthree";
String[] lines = text.split("\n");
for (String line : lines) {
System.out.println(line);
}
String text = "one\ntwo\nthree"; text.lines().forEach(IO::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")
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
Proof