Java Streams for beginners: filter, map, flatMap, sorted
What a stream is, the four steps you'll use every day, and the one surprise that trips everyone up.
On this page ⌄
A stream sends each item in a list through a few steps. You say what you want; Java runs the loop.
The loop you already know
This loop keeps the even numbers and multiplies them by ten:
List<Integer> numbers = List.of(3, 8, 1, 6, 5, 2);
List<Integer> result = new ArrayList<>();
for (int n : numbers) {
if (n % 2 == 0) {
result.add(n * 10);
}
}
// [80, 60, 20]A stream does the same job in four lines:
List<Integer> result = numbers.stream()
.filter(n -> n % 2 == 0)
.map(n -> n * 10)
.toList();
// [80, 60, 20]filter: keep what passes a test
filter takes a test (a Predicate). Items that pass stay; the rest are dropped. Six numbers in, three out.
map: change every item
map turns each item into something else. Here each word becomes its length:
List.of("kiwi", "apple", "fig").stream()
.map(String::length)
.toList();
// [4, 5, 3]Words in, numbers out. The list keeps its size; only the items change.
flatMap: lists inside a list
When each item is itself a list, flatMap unpacks them all into one stream:
List<List<Integer>> nested = List.of(List.of(3, 8), List.of(1), List.of(6, 5, 2));
nested.stream()
.flatMap(List::stream)
.toList();
// [3, 8, 1, 6, 5, 2]Three lists in, six numbers out.
sorted: put things in order
sorted is different from the others: it has to see every item before it can let the first one out.
nested.stream().flatMap(List::stream).sorted().toList();
// [1, 2, 3, 5, 6, 8]The surprise: streams are lazy
filter and map don't run when you call them. They just build a plan. Nothing moves until a terminal step such as toList(), count() or forEach() asks for a result.
Cheat sheet
| Step | What it does | In | Out |
|---|---|---|---|
filter | keeps items that pass a test | 6 | 3 |
map | changes every item | 3 words | 3 numbers |
flatMap | unpacks lists inside a list | 3 lists | 6 items |
sorted | orders items (sees all first) | 6 | 6 |
Get the next one in your inbox
New posts, videos and free PDFs. One email a week at most.