Three Forms of reducing: Identity, BinaryOperator, and Mapper
You'll learn: The three overloaded forms of the Collectors.reducing() collector and when to use each one.
Understanding the Three Overloads
Just as the Stream.reduce() method comes in three forms, the Collectors.reducing() collector mirrors this pattern. These three overloads give you flexibility when reducing values inside a collector pipeline (like with groupingBy).
Form 1: Single-Argument — BinaryOperator Only
Collectors.reducing(BinaryOperator<T> op)
Returns Optional<T> because there's no identity value. Used when the stream might be empty and you want to handle that case explicitly.
Optional<Integer> max = Stream.of(1, 5, 3)
.collect(Collectors.reducing(Integer::max));
// Result: Optional[5]
Form 2: Two-Argument — Identity + BinaryOperator
Collectors.reducing(T identity, BinaryOperator<T> op)
Provides a starting value (identity). Never returns Optional because the identity ensures there's always a result, even for empty streams.
Integer sum = Stream.of(1, 2, 3)
.collect(Collectors.reducing(0, Integer::sum));
// Result: 6 (empty stream would return 0)
Form 3: Three-Argument — Identity + Mapper + BinaryOperator
Collectors.reducing(U identity, Function<T, U> mapper, BinaryOperator<U> op)
Maps each element before reducing. Think of it as map().reduce() combined into one collector.
Integer totalLength = Stream.of("a", "bb", "ccc")
.collect(Collectors.reducing(0, String::length, Integer::sum));
// Result: 6 (1 + 2 + 3)
Key Takeaway: Collectors.reducing() has three forms: BinaryOperator-only (returns Optional), identity + BinaryOperator (guaranteed result), and identity + mapper + BinaryOperator (transform-then-reduce). Choose based on whether you need a default value and whether elements need transformation first.