String.lines()
Splits a string at line breaks and returns the lines as a stream.
Available since: Java 11
Syntax
public Stream<String> lines()Return value
Stream<String>A stream of lines without the line break characters.
Examples
Counting non-blank lines of text:
void main() {
String text = "first\n\nsecond\r\nthird";
long count = text.lines().filter(line -> !line.isBlank()).count();
IO.println(count);
}Output:
3Numbering lines:
void main() {
String poem = """
roses are red
violets are blue""";
List<String> lines = poem.lines().toList();
for (int i = 0; i < lines.size(); i++) {
IO.println((i + 1) + ": " + lines.get(i));
}
}Output:
1: roses are red
2: violets are blueNotes
It understands every kind of line break: \n, \r\n and \r. Unlike split("\n"), it does not leave \r at the end of lines from Windows files.
See also
- String.split() — Splits a string into an array of parts by a separator.
- Files.readAllLines() — Reads a text file into a list of lines.
- Text block """ — A multi-line string literal in triple quotes.
Related recipes
In the tutorial
- Text blocks and formatting — Multi-line text blocks in Java, formatting strings with formatted, String.format and printf, the %s, %d and %f specifiers and field width.