Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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:

3

Numbering 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 blue

Notes

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

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.

Thanks for reading!

Donate to the site — we work hard for you.