Collectors.toMap(): Basic Key-Value Mapping
You'll learn how to transform stream elements into a Map by extracting keys and values from each element.
What is toMap()?
Collectors.toMap() is a collector that transforms stream elements into a Map by applying two functions to each element: one that extracts the key, and another that extracts the value. Think of it like filling out a contact list where you decide which piece of information becomes the name (key) and which becomes the phone number (value).
Basic Syntax
The simplest form of toMap() takes two parameters:
Collectors.toMap(keyMapper, valueMapper)
- keyMapper: A
Functionthat extracts or computes the key from each element - valueMapper: A
Functionthat extracts or computes the value from each element
Example: Mapping Objects to Key-Value Pairs
List<String> fruits = List.of("apple", "banana", "cherry");
Map<String, Integer> fruitLengths = fruits.stream()
.collect(Collectors.toMap(
fruit -> fruit, // key: the fruit name itself
fruit -> fruit.length() // value: length of the name
));
// Result: {"apple"=5, "banana"=6, "cherry"=6}
Another Example: ID Mapping
List<Person> people = List.of(
new Person(1, "Alice"),
new Person(2, "Bob")
);
Map<Integer, String> idToName = people.stream()
.collect(Collectors.toMap(
Person::getId, // key: person's ID
Person::getName // value: person's name
));
// Result: {1="Alice", 2="Bob"}
Key Takeaway: Collectors.toMap() with keyMapper and valueMapper functions lets you convert stream elements into a Map by specifying how to derive both keys and values from each element—perfect for creating lookup tables or index structures.