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:
- T: Type of flowing element
- K: Type of keys generated by the Map.
- U: Type of values generated by the Map
- keyMapper is a function that maps stream elements to keys.
- 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}.