Java String.lines
Read a string as a stream of lines separated by LF, CR or CRLF.
A simple example
String.lines
- Start with Two lines containing A then B
- Do this Read each line
- Result 2 lines
class Main {
public static void main(String[] args) throws Exception {
System.out.println("A\nB".lines().count());
}
}
2
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.javaCount 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.
class Main {
public static void main(String[] args) throws Exception {
String note = "rice\r\ntea\n";
System.out.println(note.lines().count());
}
}
2
CRLF counts as one boundary and the final newline does not add a third entry.
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.
class Main {
public static void main(String[] args) throws Exception {
String note = "open\n\nclose";
System.out.println(note.lines().toList());
}
}
[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.
What to watch for
Line terminators are omitted. A terminator at the very end does not create another empty line.