What You'll Learn
You'll learn how to use flatMap to transform a stream of lists into a single, flat stream of individual elements.
The Core Idea
When you have a collection of collections—like a list containing other lists—and you want to process all the inner elements as one continuous stream, flatMap is your solution. Think of it like unpacking nested boxes: instead of having a stream of boxes (each containing items), you get a stream of all the items themselves.
Without flatMap, using map on a list of lists gives you Stream<List<T>>. With flatMap, you get Stream<T>.
How It Works
The flatMap operation takes each element in your stream, applies a function that returns a stream for that element, then merges (flattens) all those individual streams into one continuous stream.
List<List<String>> listOfLists = List.of(
List.of("apple", "banana"),
List.of("cherry", "date"),
List.of("elderberry")
);
// Using map would give Stream<List<String>>
// Using flatMap gives Stream<String>
List<String> allFruits = listOfLists.stream()
.flatMap(innerList -> innerList.stream())
.collect(Collectors.toList());
// Result: ["apple", "banana", "cherry", "date", "elderberry"]
Notice the lambda innerList -> innerList.stream() converts each inner list to a stream. flatMap then flattens all these streams into one.
With a method reference, this becomes even cleaner:
List<String> allFruits = listOfLists.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
Analogy
Imagine you have three boxes, each containing fruits. map would give you a stream of boxes. flatMap opens all the boxes and gives you a stream of individual fruits.
Key Takeaway:
Use flatMap when you have nested collections and need to flatten them into a single stream of elements; the lambda passed to flatMap must return a stream for each element.