STRING INSTANCE METHODS

Java String lines() method

lines() splits multiline String text into individual lines and returns them as a Stream<String>. Stream elements keep the original line order.

Displaying text lines

String tekstas = "Java\nPython\nC++";

tekstas.lines().forEach(System.out::println);
Console output

Java
Python
C++

  1. tekstas has three parts separated by newline characters, \n.
  2. lines() creates a stream with three String elements.
  3. Each contains one line's text without the \n separator.
  4. forEach(System.out::println) prints each stream element in order.

Method syntax

public Stream<String> lines()

Parts of the lines() method
PartMeaning
Calling objectMultiline String text
ParametersThe method takes no parameters
Return typeStream<String>
Element orderThe same as the original line order
Java versionAvailable since Java 11

lines() does not change the original text or return an array. It provides a lazily processed line stream supporting standard Stream API operations.

Why is lines() an instance method?

Lines are extracted from specific text, so the method is called on the selected String object:

long kiekis = zinute.lines().count();

String zinute = "Pirma eilutė\nAntra eilutė";

long eiluciuSkaicius = zinute.lines().count();

System.out.println(eiluciuSkaicius);
Console output

2

On the left, zinute identifies the text to split. We therefore do not write String.lines() : a static call would have no specific text from which to obtain lines.

Three line separators are recognized

String tekstas = "A\rB\r\nC\nD";

tekstas.lines().forEach(System.out::println);
Console output

A
B
C
D

Line endings recognized by lines()
SeparatorName
\nLF – line feed
\rCR – carriage return
\r\nCRLF – a two-character pair treated as one separator

Separators determine line boundaries but are excluded from the returned String elements.

Counting lines

String tekstas = "Pirma\nAntra\nTrečia";

long kiekis = tekstas.lines().count();

System.out.println(kiekis);
Console output

3

  1. lines() provides the lines Pirma, Antra and Trečia.
  2. count() is a terminal stream operation that counts elements.
  3. The Stream API method count() returns long, so the variable uses long kiekis.

Filtering empty and whitespace-only lines

String tekstas = "Java\n\nPython\n   \nC++";

tekstas.lines()
    .filter(eilute -> !eilute.isBlank())
    .forEach(System.out::println);
Console output

Java
Python
C++

  1. lines() provides all five lines, including an empty line and a whitespace-only line.
  2. filter() calls this for each line: isBlank().
  3. The operator ! retains only lines that are neither empty nor whitespace-only.
  4. forEach() prints the three remaining programming languages.

Transforming every line

String tekstas = "java\npython\nc++";

tekstas.lines()
    .map(String::toUpperCase)
    .forEach(System.out::println);
Console output

JAVA
PYTHON
C++

map(String::toUpperCase) converts every stream line to uppercase. The original tekstas stays unchanged: the stream provides new transformed values.

Collecting lines into a List

import java.util.List;

String tekstas = "raudona\nžalia\nmėlyna";
List<String> eilutes = tekstas.lines().toList();

System.out.println(eilutes);
System.out.println(eilutes.get(1));
Console output

[raudona, žalia, mėlyna]
žalia

lines().toList() consumes the stream and returns its elements as a list. Stream.toList() is available since Java 16; in Java 11, use lines().collect(Collectors.toList()).

An empty line in the middle is preserved

String tekstas = "A\n\nB";

System.out.println(tekstas.lines().count());
tekstas.lines().forEach(eilute ->
    System.out.println("[" + eilute + "]"));
Console output

3
[A]
[]
[B]

Two consecutive \n separators mean that between A and B there is an empty line. It becomes an empty String element, so the total line count is 3.

Empty text and a trailing separator

String tuscias = "";
String suPabaigosPerkelimu = "Java\nPython\n";

System.out.println(tuscias.lines().count());
System.out.println(suPabaigosPerkelimu.lines().count());
Console output

0
2

  1. A blank String has no lines, so the first count() returns 0.
  2. The second string has the lines Java and Python.
  3. The final \n terminates Pythonwithout creating an extra empty line, so the result is 2.

A Stream can be consumed only once

import java.util.stream.Stream;

Stream<String> eilutes = "A\nB".lines();

System.out.println(eilutes.count());
eilutes.forEach(System.out::println);
Result

2
IllegalStateException

count() completes and consumes the stream. Trying to reuse that eilutes object with forEach() causes an IllegalStateException. To repeat the operation, call tekstas.lines() again or collect the lines into a collection first.

Available since Java 11

String.lines() was added in Java 11. Java 8 and earlier cannot find this method. Those projects often use split(), but must specify line separators correctly and account for empty-result behavior.

Official Java documentation also notes that lines() can be more efficient than split("\\R")because it provides lines lazily and uses specialized separator searching.

The method cannot be called on null

String tekstas = null;

System.out.println(tekstas.lines().count());
Result

NullPointerException

null is not String object, so it has no lines or method to call. This differs from "": an empty string is a real object, and its lines() returns an empty stream.

Common mistakes

  • Expecting an array or Listwhen the method returns a Stream<String>.
  • Reusing the same stream after a terminal operation.
  • Expecting returned lines to retain their \n, \r or \r\n separators.
  • Assuming an empty String contains one empty line, although its stream has no elements.
  • Expecting an extra empty line after a trailing separator.
  • Calling the method through a null reference.

When should you use lines()?

Use lines()to process multiline text in order: count lines, remove blank ones, find entries, transform each line or collect them. It suits logs, configurations, console output and file contents already loaded into a String.