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

Collecting to Different Collection Types per Group

Use downstream collectors like toSet() or toCollection() to group into Sets or other collection types.

Collecting to Different Collection Types per Group

What you'll learn: How to use downstream collectors like toSet() or toCollection() inside groupingBy() to store each group's elements in Sets, LinkedLists, or other collection types instead of the default List.

Beyond the Default List

By default, groupingBy() collects elements into a Map<K, List<V>> — each group becomes a List. But what if you need each group stored as a Set (to eliminate duplicates), a TreeSet (for sorting), or a specific collection type?

The solution: pass a downstream collector as the second argument to groupingBy(). This collector controls how each group's elements are collected.

Common Downstream Collectors for Collection Types

Collecting Each Group into a Set

Use Collectors.toSet() to eliminate duplicates within each group:

Map<String, Set<String>> fruitsByFirstLetter = 
    fruits.stream()
          .collect(groupingBy(
              s -> s.substring(0, 1),
              toSet()
          ));
// {"A" -> ["Apple", "Apricot"], "B" -> ["Banana"]}
// Each group is now a Set instead of List

Collecting into Specific Collection Types

Use Collectors.toCollection() to specify exactly which collection implementation to use:

Map<Department, LinkedList<Employee>> employeesByDept = 
    employees.stream()
             .collect(groupingBy(
                 Employee::getDepartment,
                 toCollection(LinkedList::new)
             ));
// Each group is a LinkedList

Why This Matters

Think of it like sorting mail into bins, but you choose the bin type. Sometimes you need a regular box (List), sometimes a container that rejects duplicates (Set), or sometimes a specific organizer (TreeSet, LinkedList). The downstream collector is your bin specification.

Key Takeaway: Use downstream collectors like toSet() or toCollection(supplierFunction) as the second argument to groupingBy() to control what collection type holds each group's elements — enabling duplicate removal, ordering, or custom collection behavior per group.