Collectors
class?Collectors
is a utility class that provides various implementations of reduction operations. These include grouping elements, collecting them to different collections, summarizing them according to various criteria, etc. The different functionalities in the Collectors
class are usually used as the final operation on streams.
mapping()
methodmapping()
is a static method of the Collectors
class that returns a Collector
. It converts a Collector
accepting elements of one type to a Collector
that accepts elements of another type.
This method is generally used in multi-level reduction operations. For example, if we are given a list of persons with their name and age, we can get the list of ages for each different name.
The mapping
method is defined in the Collectors
class. The Collectors
class is defined in the java.util.stream
package. To import the Collectors
class, check the following import statement:
import java.util.stream.Collectors;
public static <T, U, A, R> Collector<T, ?, R> mapping(Function<? super T, ? extends U> mapper, Collector<? super U, A, R> downstream)
Function<? super T, ? extends U> mapper
: The mapping function to convert elements of the U
type to the T
type.Collector<? super U, A, R> downstream
: The collector to apply on the result of the mapping.This method returns a collector that applies the mapping function to the input items. It then passes the mapped results to the downstream collection.
import java.util.Arrays;import java.util.List;import java.util.Map;import java.util.stream.Collectors;import java.util.stream.Stream;public class Main {static class Person{String name;int age;public Person(String name, int age) {this.name = name;this.age = age;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +'}';}}public static void main(String[] args) {List<Person> personList = Arrays.asList(new Person("bob", 34), new Person("bob", 43),new Person("mary", 84), new Person("john", 12), new Person("bob", 22));System.out.println("Person list - " + personList);Stream<Person> personStream = personList.stream();Map<String, List<Integer>> result = personStream.collect(Collectors.groupingBy(p -> p.name,Collectors.mapping(e -> e.age, Collectors.toList())));System.out.println("Mapping result - " + result);}}
Person
class with name
and age
as class attributes.Person
objects with different names and age values called the personList
.personList
.personList
.groupingBy
reduction with the person name as the group by key. We then map the groupingBy
operation’s result to only extract the age
value from the grouped Person
objects to a list.