GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • java.evolved
  • ←
  • →

This view

  • Original page
  • New address

GeezerVison is showing javaevolved.dev — String.lines() for line splitting | java.evolved

Home / Strings / String.lines() for line splitting
Strings Beginner

String.lines() for line splitting

  • 🐛 Report a code issue
  • 🌐 Report a translation issue
  • 💡 Suggest a new pattern

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

Strings
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(IO::println);
Share 𝕏
See a problem with this code? Let us know.
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
String.lines() ↗
Proof
View proof source ↗
Related patterns
Strings Beginner

String.isBlank()

Java 8
boolean blank =
    str.trim().isEmpty();
// or: str.trim().length() == 0
Java 11+
boolean blank = str.isBlank();
// handles Unicode whitespace too
Hover to see modern ➜
JDK 11+ →
Strings Beginner

String.strip() vs trim()

Java 8
// trim() only removes ASCII whitespace
// (chars <= U+0020)
String clean = str.trim();
Java 11+
// strip() removes all Unicode whitespace
String clean = str.strip();
String left  = str.stripLeading();
String right = str.stripTrailing();
Hover to see modern ➜
JDK 11+ →
Strings Beginner

String.indent() and transform()

Java 8
String[] lines = text.split("\n");
StringBuilder sb = new StringBuilder();
for (String line : lines) {
    sb.append("    ").append(line)
      .append("\n");
}
String indented = sb.toString();
Java 12+
String indented = text.indent(4);

String result = text
    .transform(String::strip)
    .transform(s -> s.replace(" ", "-"));
Hover to see modern ➜
JDK 12+ →
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.