Collectors.mapping()
Transforms elements before passing them to another collector. Most often used inside groupingBy.
Available since: Java 8
Syntax
static <T, U, A, R> Collector<T, ?, R> mapping(Function<? super T, ? extends U> mapper, Collector<? super U, A, R> downstream)Parameters
| Parameter | Type | Description |
|---|---|---|
| mapper | Function<? super T, ? extends U> | The function that transforms an element. |
| downstream | Collector<? super U, A, R> | The collector that gathers the transformed values. |
Return value
Collector<T, ?, R>A collector that applies mapper first and then downstream.
Examples
People's names by city — each group holds just the names, not the objects:
record Person(String name, String city) {}
void main() {
List<Person> people = List.of(
new Person("Anna", "Paris"),
new Person("Oleg", "Berlin"),
new Person("Mia", "Paris"));
Map<String, List<String>> names = people.stream()
.collect(Collectors.groupingBy(Person::city, TreeMap::new,
Collectors.mapping(Person::name, Collectors.toList())));
IO.println(names);
}Output:
{Berlin=[Oleg], Paris=[Anna, Mia]}Together with joining() — a string in each group right away:
record Person(String name, String city) {}
void main() {
List<Person> people = List.of(
new Person("Anna", "Paris"),
new Person("Oleg", "Berlin"),
new Person("Mia", "Paris"));
Map<String, String> names = people.stream()
.collect(Collectors.groupingBy(Person::city, TreeMap::new,
Collectors.mapping(Person::name, Collectors.joining(", "))));
IO.println(names);
}Output:
{Berlin=Oleg, Paris=Anna, Mia}Notes
At the top level mapping() is not needed — stream.map(...).collect(...) is simpler there. Its point is to transform elements inside a group, where map() can no longer be applied. Related collectors: filtering() and flatMapping() (Java 9).
See also
- Collectors.groupingBy() — A collector that sorts elements into groups that share a key.
- Collectors.flatMapping() — Turns each element into a stream and gathers all values with another collector. See also filtering().
- Collectors.joining() — A collector that joins the strings of a stream into one.
- Stream.map() — Transforms every element of a stream.
In the tutorial
- Grouping — Grouping stream elements in Java — Collectors.groupingBy, counts and sums per group, mapping, TreeMap and partitioningBy.