The reducing Collector: General-Purpose Reduction
You'll learn how Collectors.reducing() provides a flexible, general-purpose way to perform custom reductions within the collect framework.
What Is the reducing Collector?
You've already learned about the reduce() terminal operation for folding a stream into a single value. The Collectors.reducing() collector does something similar, but works within the collect framework. This means you can use it as a downstream collector with groupingBy or partitioningBy, giving you powerful aggregation capabilities.
Think of it like this: reduce() is a standalone power tool, while Collectors.reducing() is the same tool that fits into a modular workshop system—you can combine it with other collectors.
Basic Syntax
Collectors.reducing() comes in three forms, mirroring the reduce() operation:
- With identity and accumulator:
reducing(T identity, BinaryOperator<T> op) - With mapper and accumulator:
reducing(T identity, Function<U,T> mapper, BinaryOperator<T> op) - Without identity (returns
Optional):reducing(BinaryOperator<T> op)
The most common form uses an identity value (the starting point) and a binary operator to combine elements.
When to Use It
Use Collectors.reducing() when you need custom aggregation logic as a downstream collector. For example, finding the product of values in each group, or performing complex accumulations that don't have dedicated collectors.
For simple sum/average/count operations, prefer the specialized collectors (summingInt, averagingDouble, counting()) as they're more readable and optimized.
Key Takeaway: Collectors.reducing() brings the flexibility of reduce() into the collector ecosystem, enabling custom reductions as downstream operations in grouping and partitioning scenarios.