Collectors.flatMapping()
Turns each element into a stream and gathers all values with another collector. See also filtering().
Available since: Java 9
Syntax
static <T, U, A, R> Collector<T, ?, R> flatMapping(Function<? super T, ? extends Stream<? extends U>> mapper, Collector<? super U, A, R> downstream)Parameters
| Parameter | Type | Description |
|---|---|---|
| mapper | Function<? super T, ? extends Stream<? extends U>> | A function returning a stream of values for an element. |
| downstream | Collector<? super U, A, R> | The collector for all resulting values. |
Return value
Collector<T, ?, R>A collector to use inside groupingBy and similar.
Examples
All tags of each author without duplicates:
record Post(String author, List<String> tags) {}
void main() {
List<Post> posts = List.of(
new Post("Anna", List.of("java", "streams")),
new Post("Oleg", List.of("sql")),
new Post("Anna", List.of("java", "records")));
var tagsByAuthor = posts.stream()
.collect(Collectors.groupingBy(Post::author, TreeMap::new,
Collectors.flatMapping(p -> p.tags().stream(),
Collectors.toCollection(TreeSet::new))));
IO.println(tagsByAuthor);
}Output:
{Anna=[java, records, streams], Oleg=[sql]}filtering() selects elements inside a group. Unlike filter() before grouping, empty groups are kept:
record Person(String name, String city, int age) {}
void main() {
List<Person> people = List.of(
new Person("Anna", "Paris", 30),
new Person("Oleg", "Berlin", 17),
new Person("Mia", "Paris", 15));
Map<String, Long> adults = people.stream()
.collect(Collectors.groupingBy(Person::city, TreeMap::new,
Collectors.filtering(p -> p.age() >= 18, Collectors.counting())));
IO.println(adults);
}Output:
{Berlin=0, Paris=1}Notes
flatMapping() does inside a group what flatMap() does to a whole stream. Both collectors appeared in Java 9 and usually go as the second argument of groupingBy() or partitioningBy().
See also
- Collectors.mapping() — Transforms elements before passing them to another collector. Most often used inside groupingBy.
- Collectors.groupingBy() — A collector that sorts elements into groups that share a key.
- Stream.flatMap() — Turns each element into a stream and joins all streams into one.
- Collectors.counting() — A counting collector, usually used inside `groupingBy()`.
In the tutorial
- Grouping — Grouping stream elements in Java — Collectors.groupingBy, counts and sums per group, mapping, TreeMap and partitioningBy.