Java String lines() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 11+

Definition

In Java, lines() returns a Stream<String> with one element per line of the string. A line ends at \n, \r, or \r\n, and the terminators are not included in the elements.

Because it is a stream, you can filter, map, and count lines directly. It also handles every line-ending style, which a hand-written split("\n") does not, and it does not create an empty last line for text that ends with a newline.

lines() is an instance method of java.lang.String, added in Java 11. Call it on a string, as in text.lines(); calling it on a null reference throws NullPointerException. It only reads the text; the string itself is never changed. Requires Java 11 or newer.

Syntax

Call it with no arguments and process the stream.

java
long count = text.lines().count();
text.lines().filter(line -> !line.isBlank()).forEach(System.out::println);
CallWhat it does
"a\nb".lines().count()2.
"a\r\nb\rc".lines().count()3.
"".lines().count()0.

A line terminator at the very end does not start a new line: "a\nb\n" has 2 lines. Empty lines in the middle are kept as empty strings.

Library declarations
java
public Stream<String> lines();

Parameters

ParameterDescription
Nonelines() takes no parameters.

Return Value

Return ValueDescription
Stream<String>The lines in order, without line terminators.

Java Examples

Example 1 — Read Lines with Mixed Line Endings

Unix, Windows, and old Mac terminators in a single string.

java
public class LinesMixed {
    public static void main(String[] args) {
        String text = "first\nsecond\r\nthird\rfourth";

        System.out.println("length: " + text.length());
        text.lines().forEach(line -> System.out.println("[" + line + "] " + line.length()));
    }
}

How It Works

  1. Three terminator styles. The text uses \n, \r\n, and \r; together with the words it is 26 chars long.
  2. All recognized. lines() splits at each of them, so there are exactly four lines.
  3. Terminators removed. The brackets and lengths show that no \r or \n remains inside any line.

Example 2 — lines() Versus split() at the Edges

Trailing newlines and empty text behave differently.

java
public class LinesVsSplit {
    public static void main(String[] args) {
        String text = "a\nb\n";

        System.out.println("lines():    " + text.lines().count());
        System.out.println("split(-1):  " + text.split("\n", -1).length);
        System.out.println("empty text: " + "".lines().count());
        System.out.println("just \\n:    " + "\n".lines().count());
    }
}

How It Works

  1. No phantom last line. The final \n ends line b; it does not start a third line, so lines() counts 2.
  2. split keeps the empty tail. split("\n", -1) returns 3 pieces, the last one empty.
  3. Empty text. "" has no lines at all, while a lone "\n" is one empty line.

Example 3 — Filter Blank Lines and Comments

Keep only the real entries of a small configuration text.

java
import java.util.List;
import java.util.stream.Collectors;

public class LinesFilterConfig {
    public static void main(String[] args) {
        String config = "# settings\nname=Ada\n\n   \nrole=admin\n# end\n";

        List<String> entries = config.lines()
                .filter(line -> !line.isBlank())
                .filter(line -> !line.startsWith("#"))
                .collect(Collectors.toList());

        System.out.println(entries);
        System.out.println(entries.size() + " entries");
    }
}

How It Works

  1. Six raw lines. The text holds two comments, an empty line, a line of spaces, and two entries.
  2. Two filters. isBlank() removes the empty and space-only lines, and startsWith("#") removes the comments.
  3. Collect the rest. Collectors.toList() gathers the two remaining entries into a list.

Frequently Asked Questions

A Stream of String values with one element per line. Line terminators (\n, \r, \r\n) are not included.
Java 11.
lines() recognizes all line-ending styles, returns a lazy stream, and does not produce an empty last line for text ending with a newline.
Use text.lines().count(). An empty string has 0 lines.
Collect the stream: text.lines().collect(Collectors.toList()), or text.lines().toList() on Java 16 and newer.

Next: matches()

Check whether the WHOLE string matches a regular expression.

matches() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful