What is the difference between map and flatMap in Java streams?
map transforms each element into exactly one new element. flatMap transforms each element into a stream and then merges all those streams into one flat stream, which is how you unpack lists inside lists.
Explain it simply
Suppose every student hands you a bag of pens. map is counting each bag, so you end up with a list of numbers. flatMap is emptying every bag onto one table so you have a single pile of pens.
Example
import java.util.*;
import java.util.stream.*;
List<List<Integer>> nested = List.of(List.of(1, 2), List.of(3), List.of(4, 5));
List<Integer> sizes = nested.stream()
.map(List::size)
.toList();
System.out.println(sizes); // prints: [2, 1, 2]
List<Integer> flat = nested.stream()
.flatMap(List::stream)
.map(n -> n * 10)
.toList();
System.out.println(flat); // prints: [10, 20, 30, 40, 50]What to say in the interview
"map is one-to-one, so a Stream<T> stays the same length. flatMap is one-to-many: the function must return a Stream, and the results are concatenated. A typical use is turning a list of orders into a stream of all their items, or splitting lines into words with line.split(' ') wrapped by Arrays.stream. With plain map I would be left with a Stream of Streams."
Common mistakes
- Using map where the function already returns a collection, then getting a List of Lists.