The Three Forms of reduce
What you'll learn: You'll discover the three different signatures of the reduce() operation and when to use each one.
Understanding the Three Variants
The reduce() method comes in three distinct forms, each designed for different scenarios when folding a stream into a single value.
Form 1: reduce with Identity
T reduce(T identity, BinaryOperator<T> accumulator)
This version takes an identity value (starting point) and an accumulator function. It always returns a value of type T, never null. The identity acts as the default if the stream is empty.
int sum = Stream.of(1, 2, 3, 4)
.reduce(0, (a, b) -> a + b); // Returns 10
Form 2: reduce Returning Optional
Optional<T> reduce(BinaryOperator<T> accumulator)
This version takes only an accumulator, no identity. Since an empty stream has nothing to reduce, it returns Optional<T> to handle that case safely.
Optional<Integer> sum = Stream.of(1, 2, 3, 4)
.reduce((a, b) -> a + b); // Returns Optional[10]
Form 3: reduce with Identity and Combiner
<U> U reduce(U identity, BiFunction<U,? super T,U> accumulator,
BinaryOperator<U> combiner)
This advanced version allows transforming to a different type during reduction. The combiner is crucial for parallel streams, merging partial results from different threads.
int length = Stream.of("a", "bb", "ccc")
.reduce(0,
(sum, str) -> sum + str.length(), // accumulator
(sum1, sum2) -> sum1 + sum2); // combiner
// Returns 6
Key Takeaway: Use Form 1 when you have a safe default value, Form 2 when the result might be absent, and Form 3 when reducing to a different type or optimizing parallel execution.