Skip to content
The Code Storm
All articles
Stream Storm3 min read

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.

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:

java
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:

java
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:

java
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:

java
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.

java
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

StepWhat it doesInOut
filterkeeps items that pass a test63
mapchanges every item3 words3 numbers
flatMapunpacks lists inside a list3 lists6 items
sortedorders items (sees all first)66

Get the next one in your inbox

New posts, videos and free PDFs. One email a week at most.