Streams
A stream is a sequence of values that a pipeline reads once. It is not a collection: it holds nothing, it cannot be walked twice, and nothing runs until a terminal operation asks for a result. The pipeline is the description of the work, in the order a reader would say it: keep the words longer than three letters, upper-case them, collect them into a list.
The same task twice
The loop and the pipeline below produce the same list, and the program prints both and compares them. Reading the two side by side is the fastest way to learn the pipeline:
import java.util.ArrayList;
import java.util.List;
public class LoopAndStream {
public static void main(String[] args) {
List<String> words = List.of("pear", "fig", "apple", "kiwi");
List<String> loop = new ArrayList<>();
for (String word : words) {
if (word.length() > 3) {
loop.add(word.toUpperCase());
}
}
System.out.println(loop);
List<String> stream = words.stream()
.filter(word -> word.length() > 3)
.map(String::toUpperCase)
.collect(java.util.stream.Collectors.toList());
System.out.println(stream);
System.out.println(loop.equals(stream));
}
}
javac -Xlint:all LoopAndStream.java
java LoopAndStream
[PEAR, APPLE, KIWI]
[PEAR, APPLE, KIWI]
true
The loop says where the result goes before it says what the work is: an empty list, then the condition, then the add. The pipeline says what the work is and the collection is the last step, which is why a reader can follow it without holding the name of a temporary list in mind.
The pipeline
stream() opens the pipeline on a collection, filter keeps the elements a predicate accepts, map turns each element into another value, and collect is the terminal operation that ends the pipeline and builds the result. The first three are lazy and describe the work; the fourth asks for it.
A pipeline may hold any number of lazy steps and exactly one terminal operation, and it may be read only once. A stream stored in a variable and used twice throws IllegalStateException, which lesson 092 shows; the usual form is the chain above, written as one expression.
A stream is lazy
A map with a body that prints, and no terminal operation, prints nothing. The same pipeline with a collect at the end prints a line per element, because the collect is what makes the elements flow:
import java.util.List;
import java.util.stream.Collectors;
public class Lazy {
public static void main(String[] args) {
List<String> words = List.of("a", "b");
words.stream().map(word -> {
System.out.println("mapping " + word);
return word.toUpperCase();
});
System.out.println("no terminal operation, nothing above");
System.out.println(words.stream().map(word -> {
System.out.println("mapping " + word);
return word.toUpperCase();
}).collect(Collectors.toList()));
}
}
javac -Xlint:all Lazy.java
java Lazy
no terminal operation, nothing above
mapping a
mapping b
[A, B]
The first pipeline is a description of an uppercase stream that nobody asked for, so the body never runs. That is not an optimisation: a stream does no work until a terminal operation pulls the elements through it, which is what lets the JDK fuse the steps and read the source once.
A pipeline over records
The elements may be objects, and the methods of a record read well in a pipeline: filter on a field, map to another, sort and collect. The program also sums an int field with a numeric stream, which lesson 088 covers in full:
import java.util.List;
import java.util.stream.Collectors;
public class People {
public static void main(String[] args) {
List<Person> people = List.of(
new Person("Grace", 45),
new Person("Ada", 36),
new Person("Alan", 41));
List<String> names = people.stream()
.filter(p -> p.age() > 40)
.map(Person::name)
.sorted()
.collect(Collectors.toList());
System.out.println(names);
int total = people.stream().mapToInt(Person::age).sum();
System.out.println("total age " + total);
System.out.println(people.stream().filter(p -> p.name().startsWith("A")).count());
}
}
record Person(String name, int age) {
}
javac -Xlint:all People.java
java People
[Alan, Grace]
total age 122
2
The first pipeline keeps the two people over forty, takes their names and sorts them, which gives Alan before Grace. The second sums the ages with mapToInt, which turns the stream of people into a stream of ints and so avoids a boxed sum. The third counts the names that begin with A, which is two.
When a loop is still right
A pipeline is not always the better code. A loop is the right form when the body does several things, when the state has to change between elements, when an index is needed, or when the operation must break out early with a value that depends on where it stopped. A pipeline is the right form when the work is a filter, a map, a sort, a group or a sum.
The cost of the pipeline is the objects it passes between steps and the lambda call at each one, which the JIT usually removes and a very hot loop sometimes does not. The measurement that decides is lesson 091 for the parallel case; for the sequential one, write the pipeline when it is clearer and keep the loop when the pipeline would need a comment.
Exercises
- Rewrite LoopAndStream without filter, using an if inside map, and explain why the first form is better.
- Print the words of LoopAndStream that contain an a, sorted and in lower case.
- Take the pipeline of Lazy, remove the collect and add forEach, and compare the output.
- Sum the lengths of the names of People with a pipeline.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a stream hold?
Answer
Nothing: it is a description of a sequence that is read once
The elements come from the source when a terminal operation pulls them.
-
Which step is a terminal operation?
Answer
collect
filter, map and sorted return another lazy stream; collect ends the pipeline.
-
When does the body of a
maprun?Answer
When a terminal operation asks for the elements
The pipeline is lazy, so nothing runs until a terminal operation pulls.
-
What does this program print?
import java.util.List; import java.util.stream.Collectors; public class Q1 { public static void main(String[] args) { List<Integer> numbers = List.of(1, 2, 3, 4); List<Integer> even = numbers.stream() .filter(n -> n % 2 == 0) .collect(Collectors.toList()); System.out.println(even); } }Answer
[2, 4]
The filter keeps the even numbers and the collect builds the list.
-
What does this program print?
import java.util.List; import java.util.stream.Collectors; public class Q2 { public static void main(String[] args) { List<String> words = List.of("a", "bb"); System.out.println(words.stream().map(String::length).collect(Collectors.toList())); } }Answer
[1, 2]
map turns each word into its length, and the list holds the two numbers.
-
What does this program print?
import java.util.List; public class Q3 { public static void main(String[] args) { List<String> words = List.of("a", "b"); words.stream().map(w -> { System.out.println(w); return w; }); System.out.println("done"); } }Answer
done
There is no terminal operation, so the map body never runs.
-
What does this program print?
import java.util.List; public class Q4 { public static void main(String[] args) { List<Integer> numbers = List.of(1, 2, 3); System.out.println(numbers.stream().map(n -> n * 10).count()); } }Answer
3
count is a terminal operation that answers how many elements the stream has.
-
What does this program print?
import java.util.List; import java.util.stream.Collectors; public class Q5 { public static void main(String[] args) { List<String> words = List.of("pear", "fig", "apple"); System.out.println(words.stream().filter(w -> w.length() > 3).sorted().collect(Collectors.toList())); } }Answer
[apple, pear]
Two words are longer than three letters, and sorted puts them alphabetically.
-
What does
mapToIntgive thatmapdoes not?Answer
A stream of primitive ints, with sum and average and no boxing
The numeric stream has the arithmetic terminal operations, which the object stream does not.
-
When is a loop clearer than a pipeline?
Answer
When the body does several things or needs the index or an early exit
The pipeline has one expression per step, so work that does not fit a step belongs in a loop.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev