Video in progress
Explain the difference between map() and flatMap() with an example.
map turns each element into one new value. flatMap produces a stream from each element and merges those streams into one flat stream, which is how you "unwrap" a nested structure.
📖 Answer
Say each order has several items, and you need the list of items across all orders.
record Order(long id, List<String> items) {}
List<Order> orders = List.of(
new Order(1, List.of("non", "sut")),
new Order(2, List.of("choy")));
// map: Stream<List<String>>, a list of lists
List<List<String>> nested = orders.stream().map(Order::items).toList();
// [[non, sut], [choy]]
// flatMap: Stream<String>, flat
List<String> flat = orders.stream()
.flatMap(o -> o.items().stream())
.toList();
// [non, sut, choy]
The rule: the function passed to map returns T -> R, while the function passed to flatMap returns T -> Stream<R>.
Other common cases:
- splitting text into words:
lines.flatMap(l -> Arrays.stream(l.split(" "))); - taking only the present values from a list of
Optionals:.flatMap(Optional::stream)(Java 9+).
Optional has map and flatMap too, with the same logic: if the function itself returns an Optional, use flatMap, otherwise you end up with an Optional<Optional<T>>.
Sign up to mark studied questions and save your progress.