Sub topic 12
Flattening Nested Data with flatMap
Sometimes your data comes in layers. A list might hold other lists. A list of sentences might hold many words. In this chapter you learn how flatMap turns layered data into one simple stream.
The Problem with Nested Data
Nested data is data stored inside other data. A List<List<Integer>> is a list where each element is itself a list of numbers.
Say you want every number in one plain list. If you use map with List::stream, each inner list becomes its own stream. You end up with a Stream<Stream<Integer>>, which is a stream of streams. That is hard to work with.
What flatMap Does
flatMap is an intermediate operation. For each element, it makes a small stream. Then it joins all those small streams into one big stream. The name combines two steps: "map" each element to a stream, then "flatten" the results into one level.
Worked Example: A List of Lists
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]
}
}Here is what happens, step by step:
nested.stream()makes a stream of three lists.flatMap(List::stream)turns each list into a stream of its numbers and merges them.collect(Collectors.toList())gathers the numbers into one list.
Worked Example: Sentences into Words
flatMap also works when you build the inner stream yourself. This program splits each sentence into words.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class WordsExample {
public static void main(String[] args) {
List<String> sentences = List.of("I like Java", "streams are fun");
List<String> words = sentences.stream()
.flatMap(s -> Arrays.stream(s.split(" ")))
.collect(Collectors.toList());
System.out.println(words); // [I, like, Java, streams, are, fun]
}
}The lambda takes one sentence. It splits the sentence into an array of words and then turns that array into a stream with Arrays.stream.
map Versus flatMap
| Operation | Function returns | Result for 3 inputs |
|---|---|---|
| `map` | One value per element | Exactly 3 elements |
| `flatMap` | A stream per element | Any number of elements, merged |
Exercise
You have List<List<String>> teams = List.of(List.of("Ann", "Bo"), List.of("Cy")). Write one pipeline that produces a single List<String> of all names.
Show answer
teams.stream().flatMap(List::stream).collect(Collectors.toList()) produces [Ann, Bo, Cy]. flatMap turns each inner list into a stream and merges them into one stream of names.
Exercise
How many elements does the stream contain after applying flatMap(List::stream) to List.of(List.of(), List.of(7, 8), List.of(9))?
Show answer
Three elements: 7, 8, and 9. The empty inner list adds nothing to the merged stream.