Chaining Multiple Downstream Collectors
What you'll learn: How to combine several downstream collectors within a single grouping operation to perform multiple aggregations simultaneously.
The Core Idea
When you group data with groupingBy or partitioningBy, you're not limited to a single downstream operation. You can chain multiple downstream collectors together by using collectingAndThen, mapping, and other collectors in creative combinations. This lets you build sophisticated aggregation pipelines that transform, filter, and aggregate data in multiple ways—all within one pass through the stream.
Think of it like a factory assembly line: instead of sending your grouped items through just one processing station, you route them through multiple stations, each applying its own transformation or calculation before producing the final result.
Building Complex Pipelines
The key is recognizing that downstream collectors themselves accept downstream collectors. For example, you might:
- First filter or map the grouped elements
- Then collect them with another downstream operation
- Finally post-process with
collectingAndThen
Map<Department, Integer> result = employees.stream()
.collect(groupingBy(
Employee::getDepartment,
collectingAndThen(
mapping(
Employee::getSalary,
summingInt(Integer::intValue)
),
sum -> sum / 1000 // Convert to thousands
)
));
This example groups employees by department, extracts salaries, sums them, and then divides by 1000—three operations chained together.
You can nest even deeper by combining filtering, mapping, and aggregation collectors to create multi-stage transformations within each group.
Key Takeaway: Chaining downstream collectors lets you compose multiple transformation and aggregation steps within a single groupingBy or partitioningBy operation, creating powerful data processing pipelines without multiple stream passes.