Collectors.flatMapping()
Use flatMapping() to flatten inside a grouping collector.
Code Comparison
✕ Java 8
// Flatten within a grouping collector
// Required complex custom collector
Map<String, Set<String>> tagsByDept =
// no clean way in Java 8
✓ Java 9+
var tagsByDept = employees.stream()
.collect(groupingBy(
Emp::dept,
flatMapping(
e -> e.tags().stream(),
toSet()
)
));
Why the modern way wins
Composable
Works as a downstream collector inside groupingBy.
One pass
Flatten and group in a single stream traversal.
Nestable
Combine with other downstream collectors.
Old Approach
Nested flatMap
Modern Approach
flatMapping()
Since JDK
9
Difficulty
intermediate
JDK Support
Collectors.flatMapping()
Available
Widely available since JDK 9 (Sept 2017)
How it works
Collectors.flatMapping() applies a one-to-many mapping as a downstream collector. It's the collector equivalent of Stream.flatMap() — useful inside groupingBy or partitioningBy.