Course contentsShow
← Java
Lesson 2223 of 2,87043. String Handling in DepthFree lesson

The lines Method: Stream-Based Line Processing

Learn how lines() returns a Stream<String> of individual lines, enabling functional-style text processing.

The lines Method: Stream-Based Line Processing

You'll learn how to process multi-line strings functionally using the lines() method, which breaks text into individual lines as a stream.

When working with multi-line text, you often need to process each line separately—filtering, transforming, or analyzing them individually. The lines() method, introduced in Java 11, converts a String containing line breaks into a Stream<String> where each element represents one line.

What lines() Does

Think of lines() as turning a multi-page document into a conveyor belt where each page passes by separately. Instead of manually splitting on \n or \r\n, lines() handles all common line terminators (\n, \r, and \r\n) automatically and gives you a stream you can process with functional operations.

String text = "apple\nbanana\ncherry";

text.lines()
    .forEach(System.out::println);
// Output:
// apple
// banana
// cherry

Stream-Based Processing Power

Since lines() returns a Stream<String>, you can chain all the stream operations you know—filtering, mapping, counting, collecting:

String data = "line 1\n\nline 3\n";

long nonEmptyLines = data.lines()
                         .filter(line -> !line.isEmpty())
                         .count();
// Result: 2

You can also transform each line:

String report = "total: 100\ncount: 5\nerror: none";

report.lines()
      .map(String::toUpperCase)
      .forEach(System.out::println);
// TOTAL: 100
// COUNT: 5
// ERROR: NONE

Key Takeaway:
The lines() method transforms a multi-line String into a Stream<String> of individual lines, enabling clean, functional-style text processing without manual splitting or line-terminator handling.