What is the usage of collectors.toMap in Java?

In Java, the Collectors.toMap() method is used to collect stream elements into a Map collection. It takes two parameters, keyMapper and valueMapper, to specify how to generate keys and values for the Map.

grammar

public static <T, K, U> Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper)

Parameter explanation:

  1. T: Type of flowing element
  2. K: Type of keys generated by the Map.
  3. U: Type of values generated by the Map
  4. keyMapper is a function that maps stream elements to keys.
  5. valueMapper: a function that maps stream elements to values

Suppose we have a Person class that includes properties for name and age. Now we have a List of Person objects, and we want to create a Map where the names of the Person objects are used as keys and their ages as values.

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Person> persons = List.of(
                new Person("Alice", 25),
                new Person("Bob", 30),
                new Person("Charlie", 35)
        );

        Map<String, Integer> map = persons.stream()
                .collect(Collectors.toMap(Person::getName, Person::getAge));
        System.out.println(map);
    }
}

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

The output result is:

{Alice=25, Bob=30, Charlie=35}

In the example above, a Map was created from the List of Person objects with name as the key and age as the value using Collectors.toMap(Person::getName, Person::getAge). The output result is {Alice=25, Bob=30, Charlie=35}.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds