Streams: flatMapping collector groups and flattens together

Collectors.flatMapping (Java 9) is the downstream answer to flatMap - group by a key while flattening each group's nested collection.

Code
record Dev(String team, List<String> skills) {}
var devs = List.of(new Dev("core", List.of("java", "sql")),
                   new Dev("core", List.of("java", "kafka")),
                   new Dev("web", List.of("js")));

Map<String, Set<String>> skillsByTeam = devs.stream().collect(
        Collectors.groupingBy(Dev::team, TreeMap::new,
                Collectors.flatMapping(d -> d.skills().stream(), Collectors.toCollection(TreeSet::new))));

System.out.println(skillsByTeam);
Output
{core=[java, kafka, sql], web=[js]}
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-30