Collecting to Maps with Complex Value Types
You'll learn how to build maps where values aren't just simple primitives or strings, but rich objects, collections, or computed results from your stream data.
The Core Idea
So far, you've seen toMap() create maps with simple values—perhaps mapping IDs to names or keys to counts. But real-world data often demands more: what if you want a map where each value is a list of related items, an object you've constructed, or a calculated statistic? Java's Collectors.toMap() handles this by letting you specify a value mapper function that produces any type you need.
Think of it like organizing a library: instead of mapping author names to a single book title, you might map each author to a collection of all their books, or to a custom AuthorStats object containing their publication count and average rating.
Building Rich Value Types
The value mapper (the second argument to toMap()) is a function that transforms each stream element into whatever you need:
// Map person IDs to Person objects themselves
Map<Integer, Person> peopleById = people.stream()
.collect(Collectors.toMap(Person::getId, person -> person));
// Map department names to lists of employees
Map<String, List<Employee>> empsByDept = employees.stream()
.collect(Collectors.toMap(
Employee::getDepartment,
emp -> new ArrayList<>(List.of(emp)), // wrap in list
(list1, list2) -> {
list1.addAll(list2);
return list1;
}
));
Notice how the merge function becomes crucial when values are mutable objects or collections—you must define how to combine them when duplicate keys appear.
Key Takeaway: Use Collectors.toMap() with custom value mappers to create maps with complex values like objects, collections, or computed results—just remember to provide an appropriate merge function when duplicates are possible.