JavaIntermediate#java8#streams

What is the difference between map() and flatMap() in streams?

map() transforms each element to another value one-to-one, potentially producing nested structures. flatMap() flattens nested structures (like Stream<List<T>>) into a single flat stream by merging inner streams.

Example
List<List<Integer>> nested = List.of(List.of(1,2), List.of(3,4));
List<Integer> flat = nested.stream()
  .flatMap(List::stream)
  .collect(Collectors.toList());
// [1, 2, 3, 4]

Related Questions

1
JavaBeginner#streams

What is the difference between Collectors.toList() and Collectors.toSet()?

Open
2
JavaIntermediate#streams

How do you group elements using Collectors.groupingBy?

Open
3
JavaIntermediate#streams

What is the difference between findFirst() and findAny() in streams?

Open