Course contentsShow
← Java
Lesson 1555 of 2,87034. Collectors in DepthFree lesson

Specifying Map Implementation with toMap()

Use the four-argument toMap() to collect into specific Map types like TreeMap or LinkedHashMap.

Specifying Map Implementation with toMap()

You'll learn: How to collect stream elements into a specific Map type (like TreeMap or LinkedHashMap) instead of the default implementation.

Why Control the Map Type?

By default, toMap() returns whatever Map implementation the JDK chooses—typically a HashMap. But sometimes you need specific behavior: sorted keys (TreeMap), insertion-order preservation (LinkedHashMap), or thread-safe collections (ConcurrentHashMap).

The Four-Argument toMap() Overload

The most powerful form of toMap() accepts four arguments:

Collectors.toMap(
    keyMapper,
    valueMapper,
    mergeFunction,
    mapSupplier
)

The fourth parameter, mapSupplier, is a function that creates the desired Map instance. Think of it as telling the collector: "Use this specific box to store my results."

Practical Example

Map<String, Integer> sortedMap = employees.stream()
    .collect(Collectors.toMap(
        Employee::getName,
        Employee::getAge,
        (existing, replacement) -> existing,
        TreeMap::new  // Specifies TreeMap implementation
    ));

For insertion-order preservation:

Map<String, Integer> orderedMap = employees.stream()
    .collect(Collectors.toMap(
        Employee::getName,
        Employee::getAge,
        (existing, replacement) -> existing,
        LinkedHashMap::new  // Preserves stream order
    ));

The mapSupplier (like TreeMap::new) is a method reference that constructs an empty map of your chosen type.

When to Use This

Use the four-argument form when you need:

  • Sorted keys (TreeMap)
  • Insertion order (LinkedHashMap)
  • Thread safety (ConcurrentHashMap in concurrent contexts)
  • Any specialized Map implementation

Key Takeaway: The four-argument toMap() lets you specify the exact Map implementation by passing a constructor reference as the fourth argument, giving you full control over ordering and behavior.