Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
mapping
collectors

What is Collectors.mapping() in Java?

abhilash

What is the 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.

The mapping() method

mapping() 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;

Syntax


public static <T, U, A, R> Collector<T, ?, R> mapping(Function<? super T, ? extends U> mapper, Collector<? super U, A, R> downstream)

Parameters

  • 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.

Return value

This method returns a collector that applies the mapping function to the input items. It then passes the mapped results to the downstream collection.

Code

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;
        }

        @Override
        public 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);

    }
}
Implementation of the mapping() method

Explanation

  • Lines 1-6: We import the relevant packages.
  • Lines 10-26: We define a Person class with name and age as class attributes.
  • Lines 28-29: We create a list of the Person objects with different names and age values called the personList.
  • Line 31: We print the personList.
  • Line 33: We create a stream from the personList.
  • Line 35-36: We first apply the 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.
  • Line 38: We print the map of a person’s name to a set of persons’ ages with the same name to the console.

RELATED TAGS

java
communitycreator
mapping
collectors
RELATED COURSES

View all Courses

Keep Exploring