Downstream Collectors: Transforming Grouped Values
What you'll learn: How to apply additional collectors to grouped values, transforming them from their default List form into something more useful.
When you use groupingBy(), by default it collects each group's elements into a List. But what if you want the count of items in each group instead? Or the sum of a particular field? This is where downstream collectors come in.
The Core Idea
A downstream collector is a second collector you pass to groupingBy() that processes the values within each group. Think of it like a two-stage filter: first you sort mail into bins by zip code (the grouping), then you count how many letters are in each bin (the downstream collector).
The syntax looks like this:
Collectors.groupingBy(classifierFunction, downstreamCollector)
Common Downstream Collectors
Instead of getting Map<Key, List<Value>>, you might want:
- Counting items per group: Use
Collectors.counting()to getMap<Key, Long> - Summing values: Use
Collectors.summingInt()or similar - Finding averages: Use
Collectors.averagingDouble() - Collecting to Sets: Use
Collectors.toSet()to avoid duplicates
Example Pattern
// Count how many people live in each city
Map<String, Long> countByCity = people.stream()
.collect(Collectors.groupingBy(
Person::getCity, // classifier
Collectors.counting() // downstream collector
));
This transforms each group from a List<Person> into a simple count (Long).
Key Takeaway: Downstream collectors let you transform grouped values into aggregated results (counts, sums, averages) or different collection types, making groupingBy() far more powerful than simple list-based grouping.