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

Custom Map Types with groupingBy Supplier

Provide a Map supplier to groupingBy to control the type of Map returned, such as TreeMap or LinkedHashMap.

Custom Map Types with groupingBy Supplier

What you'll learn: How to control the exact type of Map returned by groupingBy using a supplier function.

By default, groupingBy returns a HashMap. But what if you need your groups sorted by key, or you want to preserve insertion order? You can supply a custom Map implementation as the first parameter.

The Three-Argument groupingBy Overload

The full signature of groupingBy with a supplier looks like this:

Collectors.groupingBy(
    Function classifier,
    Supplier<Map> mapFactory,
    Collector downstream
)

The mapFactory is a supplier that creates the specific Map type you want. Common choices include TreeMap::new for sorted keys or LinkedHashMap::new for insertion-order preservation.

When and Why to Use Custom Map Types

  • TreeMap: When you need groups sorted by key (alphabetically, numerically, etc.)
  • LinkedHashMap: When you want to preserve the order keys were first encountered
  • ConcurrentHashMap: For thread-safe operations in concurrent environments

Example with TreeMap (sorted alphabetically by first letter):

Map<Character, List<String>> sortedGroups = 
    Stream.of("apple", "banana", "apricot", "cherry")
        .collect(Collectors.groupingBy(
            s -> s.charAt(0),
            TreeMap::new,
            Collectors.toList()
        ));
// Result: {a=[apple, apricot], b=[banana], c=[cherry]}
// Keys are in sorted order: a, b, c

Think of It Like Choosing Your Container

Imagine sorting mail into bins. A HashMap is like randomly arranged bins—fast but unordered. A TreeMap is like alphabetically labeled bins on a shelf. A LinkedHashMap remembers which bin you filled first.

Key Takeaway: Use the three-argument groupingBy with a Map supplier to control the returned Map type—TreeMap::new for sorted keys, LinkedHashMap::new for insertion order, or any other Map implementation your use case requires.