flatMap
- Java course
- Advanced
- Lesson 5/82
- 5 min
Learn to flatten nested streams with flatMap.
Flattening a stream: flatMap
map turns each element into a single new value. flatMap turns each element into a stream of multiple values and then merges those streams into one. You use it to flatten nested lists.
Example: lists.stream().flatMap(List::stream). Each inner list is turned into a stream, then the streams are merged into a single stream. The result is a Stream<Integer> containing all elements of the inner lists in order.
Common patterns with flatMap
Two cases come up most often with flatMap: flattening nested collections and producing several values from a single object.
For example, if an Order object holds an items list, orders.stream().flatMap(o -> o.items().stream()) gives all items of all orders in a single stream. Another example: turning a string into a stream of characters with str.chars().mapToObj(c -> (char) c); this is also a one-to-many transform.
Practice Flatten nested lists
Create a List<List<Integer>> with three inner lists: List.of(1, 2, 3), List.of(4, 5), List.of(6). Flatten the stream with flatMap(List::stream) and collect with toList. Then print each element on its own line using System.out::println.
Starter code
import java.util.List;
// Flatten the nested lists
// Open each inner list with flatMap
// Print each element on its own lineSample solution
import java.util.List;
public class FlattenLists {
public static void main(String[] args) {
List<List<Integer>> nested = List.of(
List.of(1, 2, 3),
List.of(4, 5),
List.of(6)
);
List<Integer> flat = nested.stream()
.flatMap(List::stream)
.toList();
flat.forEach(System.out::println);
}
}Expected output
1 2 3 4 5 6
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the map vs flatMap difference
| Term | Meaning |
|---|---|
map |
One-to-one transform |
flatMap |
One-to-many transform |
List::stream |
Opens an inner list |
Stream.of |
Creates a stream |
2 Which method merges nested lists into a single stream?
- flatMap Correct answer
- map
- filter
- reduce
Explanation: FlatMap. It flattens nested streams.
3 Complete the flatMap call
List<Integer> flat = nested.stream()
.flatMap(____)
.toList();
List<Integer> flat = nested.stream()
.flatMap(List::stream)
.toList();
Explanation: List::stream opens each inner list into a stream.