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);Java
Python
C++
tekstashas three parts separated by newline characters,\n.lines()creates a stream with threeStringelements.- Each contains one line's text without the
\nseparator. forEach(System.out::println)prints each stream element in order.
Method syntax
public Stream<String> lines()
| Part | Meaning |
|---|---|
| Calling object | Multiline String text |
| Parameters | The method takes no parameters |
| Return type | Stream<String> |
| Element order | The same as the original line order |
| Java version | Available 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);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);A
B
C
D
| Separator | Name |
|---|---|
\n | LF – line feed |
\r | CR – carriage return |
\r\n | CRLF – 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);3
lines()provides the lines Pirma, Antra and Trečia.count()is a terminal stream operation that counts elements.- The Stream API method
count()returnslong, so the variable useslong kiekis.
Filtering empty and whitespace-only lines
String tekstas = "Java\n\nPython\n \nC++";
tekstas.lines()
.filter(eilute -> !eilute.isBlank())
.forEach(System.out::println);Java
Python
C++
lines()provides all five lines, including an empty line and a whitespace-only line.filter()calls this for each line:isBlank().- The operator
!retains only lines that are neither empty nor whitespace-only. forEach()prints the three remaining programming languages.
Transforming every line
String tekstas = "java\npython\nc++";
tekstas.lines()
.map(String::toUpperCase)
.forEach(System.out::println);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));[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 + "]"));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());0
2
- A blank
Stringhas no lines, so the firstcount()returns0. - The second string has the lines Java and Python.
- The final
\nterminates Pythonwithout creating an extra empty line, so the result is2.
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);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());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 aStream<String>. - Reusing the same stream after a terminal operation.
- Expecting returned lines to retain their
\n,\ror\r\nseparators. - Assuming an empty
Stringcontains one empty line, although its stream has no elements. - Expecting an extra empty line after a trailing separator.
- Calling the method through a
nullreference.
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.