Strings beginner

String.lines() for line splitting

Use String.lines() to split text into a stream of lines without regex overhead.

✕ 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);

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
String.lines() for line splitting
Available

Available since JDK 11 (September 2018).

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.

Share 𝕏 🦋 in