Specifying the Map Implementation with toMap
What you'll learn: How to control the exact type of Map returned by toMap() by providing your own Supplier.
Why This Matters
By default, Collectors.toMap() returns whatever Map implementation it chooses (typically HashMap). But sometimes you need a specific type—maybe a TreeMap for sorted keys, or a LinkedHashMap to preserve insertion order.
The Four-Argument toMap
The full signature of toMap() includes a fourth parameter—a Supplier that creates the Map instance:
Collectors.toMap(
keyMapper,
valueMapper,
mergeFunction,
mapSupplier
)
This Supplier is a factory that tells the collector, "Create this type of Map for me."
Common Examples
TreeMap (sorted keys):
Map<String, Integer> sorted = people.stream()
.collect(Collectors.toMap(
Person::getName,
Person::getAge,
(age1, age2) -> age1,
TreeMap::new // Supplier for TreeMap
));
LinkedHashMap (insertion order):
Map<String, Integer> ordered = people.stream()
.collect(Collectors.toMap(
Person::getName,
Person::getAge,
(age1, age2) -> age1,
LinkedHashMap::new // Preserves stream order
));
Think of It Like a Container Factory
The Supplier is like telling a factory, "Use this specific box design." Without it, you get the default box. With it, you get exactly the container you need—sorted, ordered, or any custom Map implementation.
Key Takeaway:
Use the four-argument toMap() with a Supplier (like TreeMap::new or LinkedHashMap::new) to control the exact Map implementation returned from your stream.