Sub topic 12
Flattening Nested Data with flatMap
Real data is often nested. A school has classes, and each class has students. An order has many items. A text file has lines, and each line has words. Sometimes you want to work with the inner things directly, such as every student or every word, as one long sequence.
The flatMap operation does this. It is an intermediate operation that turns each element into a small stream of its own, then joins all those small streams into one stream. This step is called "flattening."
Why map Is Not Enough
You already know map. It takes one element and gives back exactly one new element. That is a one-to-one change.
Now say you have a list of lists. You want one stream of numbers. A first try with map looks like this:
- Each inner list becomes a stream with
List::stream. mapkeeps that result as one element.- You end up with a stream whose elements are streams. Its type is
Stream<Stream<Integer>>.
That is a stream of boxes, not a stream of numbers. You can't sum it or sort it as numbers. flatMap fixes this by opening each box and pouring its contents into a single stream.
The program below runs both versions so you can compare the results.
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class MapVsFlatMap {
public static void main(String[] args) {
List<List<Integer>> nested = List.of(
List.of(1, 2),
List.of(3));
// map: each inner list becomes ONE element (a stream)
List<Stream<Integer>> boxes = nested.stream()
.map(List::stream)
.collect(Collectors.toList());
System.out.println(boxes.size()); // 2
// flatMap: the inner streams are merged into one
List<Integer> numbers = nested.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
System.out.println(numbers); // [1, 2, 3]
}
}With map, you get 2 elements, and each one is a stream. With flatMap, you get 3 elements, and each one is a number.
| Operation | What the function returns | Elements out per element in | Result type for `List<List<Integer>>` |
|---|---|---|---|
| `map` | One value | Exactly 1 | `Stream<Stream<Integer>>` |
| `flatMap` | A stream of values | 0, 1, or many | `Stream<Integer>` |
A Worked Example: Flattening a List of Lists
Here is the full basic pattern. The source is a list of lists. flatMap merges the lists, and collect gathers the result.
import java.util.List;
import java.util.stream.Collectors;
public class FlatMapExample {
public static void main(String[] args) {
List<List<Integer>> nested = List.of(
List.of(1, 2),
List.of(3),
List.of(4, 5, 6));
List<Integer> flat = nested.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
System.out.println(flat); // [1, 2, 3, 4, 5, 6]
}
}Read the pipeline step by step:
nested.stream()makes a stream of three elements. Each element is aList<Integer>..flatMap(List::stream)callsstream()on each inner list.List::streamis a method reference, a short way to write the lambdalist -> list.stream().- The three small streams are joined in order into one stream of six numbers.
.collect(Collectors.toList())puts them into a new list.
The order is kept. All elements of the first inner list come first, then all elements of the second, and so on.
Splitting Text into Words
Text is another common case. Each line is one element, but you want the words. String.split returns an array, and Arrays.stream turns that array into a stream.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class WordsExample {
public static void main(String[] args) {
List<String> lines = List.of(
"the cat sat",
"the dog ran");
List<String> words = lines.stream()
.flatMap(line -> Arrays.stream(line.split(" ")))
.distinct()
.collect(Collectors.toList());
System.out.println(words); // [the, cat, sat, dog, ran]
}
}After flatMap, the stream holds six words. The word "the" appears twice. distinct removes the duplicate, so five words remain. You can chain any other operation after flatMap, just like after map.
Reaching Inside Objects
Often the nested data sits inside an object. In the example below, each Order holds a list of item names. To list every item from every order, you flatten the item lists.
import java.util.List;
import java.util.stream.Collectors;
public class OrderItemsExample {
static class Order {
private final String id;
private final List<String> items;
Order(String id, List<String> items) {
this.id = id;
this.items = items;
}
String getId() {
return id;
}
List<String> getItems() {
return items;
}
}
public static void main(String[] args) {
List<Order> orders = List.of(
new Order("A", List.of("pen", "ink")),
new Order("B", List.of()),
new Order("C", List.of("paper", "pen")));
List<String> allItems = orders.stream()
.flatMap(order -> order.getItems().stream())
.collect(Collectors.toList());
System.out.println(allItems); // [pen, ink, paper, pen]
System.out.println(allItems.size()); // 4
}
}Order "B" has no items. Its empty list becomes an empty stream, and an empty stream adds nothing. You don't need any special code for empty inner lists.
Edge Cases to Watch
Empty inner collections
As you just saw, empty inner collections add zero elements to the result. This is safe and normal.
Null inner collections
A null list is different. If getItems() returns null, then order.getItems().stream() throws a NullPointerException, because you can't call a method on null. Guard against it like this:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class NullSafeFlatMap {
public static void main(String[] args) {
List<List<String>> lists = new ArrayList<>();
lists.add(Arrays.asList("a", "b"));
lists.add(null);
lists.add(Arrays.asList("c"));
List<String> flat = lists.stream()
.flatMap(list -> list == null ? Stream.empty() : list.stream())
.collect(Collectors.toList());
System.out.println(flat); // [a, b, c]
}
}Stream.empty() makes a stream with no elements. So a missing list is treated the same as an empty one. The example uses ArrayList because List.of does not allow null elements.
Deeper nesting
flatMap removes one level of nesting at a time. A List<List<List<Integer>>> needs two flatMap calls to become a Stream<Integer>.
Numbers without boxing
When the inner values are numbers you plan to sum or average, flatMapToInt, flatMapToLong, and flatMapToDouble produce a primitive stream directly. The chapter on IntStream, LongStream, and DoubleStream covers those stream types.
Quick Rule of Thumb
- Use
mapwhen each element turns into exactly one new element. - Use
flatMapwhen each element turns into zero, one, or many elements, and you want them all in one stream. - If your result type looks like
Stream<Stream<T>>orList<List<T>>and you wanted a flat list, you probably neededflatMap.
Exercise
You have List<List<String>> teams = List.of(List.of("Ann", "Bo"), List.of("Cy")). Write a pipeline that produces the list [Ann, Bo, Cy].
Show answer
teams.stream().flatMap(List::stream).collect(Collectors.toList()). flatMap calls stream() on each inner list and merges the results into one stream of names, which collect gathers into a list.
Exercise
What does this print? List.of("a b", "", "c").stream().flatMap(s -> Arrays.stream(s.split(" "))).count()
Show answer
It prints 4. "a b" splits into "a" and "b". The empty string "" split on a space gives an array with one empty string, so it adds one element. "c" adds one more. The total is 2 + 1 + 1 = 4.
Exercise
A pipeline uses .map(order -> order.getItems().stream()) and the code that follows expects strings, but it fails to compile. Why, and what is the fix?
Show answer
map keeps each returned stream as one element, so the result is a Stream<Stream<String>>, not a Stream<String>. Replace map with flatMap so the inner streams are merged into a single Stream<String>.