Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

ParameterTypeDescription
mapperFunction<? super T, ? extends U>The function that transforms an element.
downstreamCollector<? 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

In the tutorial

  • Grouping — Grouping stream elements in Java — Collectors.groupingBy, counts and sums per group, mapping, TreeMap and partitioningBy.

Thanks for reading!

Donate to the site — we work hard for you.