Library contents

Java String.lines

Read a string as a stream of lines separated by LF, CR or CRLF.

A simple example

String.lines

  1. Start with Two lines containing A then B
  2. Do this Read each line
  3. Result 2 lines
The newline separates the two records. The letters are the contents of those records.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("A\nB".lines().count());
    }
}
Output
2

Syntax

Java syntax
public Stream<String> lines()
JDK 21 method signatures (1)
public Stream<String> lines()
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Count entries in a two-line shopping note

A handover or shopping note stores one entry per line. The display needs a count of the entries after interpreting line boundaries rather than counting the entire note as one item.

From the programString note = "rice\r\ntea\n"
Result2
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String note = "rice\r\ntea\n";
        System.out.println(note.lines().count());
    }
}
Output
2

CRLF counts as one boundary and the final newline does not add a third entry.

Advertisements

Keep a blank line in a shift handover

A line-based import may include a blank record or a last record without a terminating newline. Distinguish a legitimate line from the end of the input so the import keeps the right number of rows.

From the programString note = "open\n\nclose"
Result[open, , close]
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String note = "open\n\nclose";
        System.out.println(note.lines().toList());
    }
}
Output
[open, , close]

The empty line between the two words survives.

Read a studio checklist

A stage manager places each job on its own line. Count the lines of work in the saved note. The final line has no trailing newline.

GivenOpen / Test / Close
Worked result3

What to watch for

Line terminators are omitted. A terminator at the very end does not create another empty line.

Documentation for String.lines