What You'll Learn
You'll learn how to use the reduce operation with an identity value to safely fold a stream into a single result, even when the stream is empty.
Understanding the Identity-Based reduce
The reduce(T identity, BinaryOperator<T> accumulator) form is the safest version of reduce. It takes two arguments:
- Identity value: The starting point for the reduction and the default result if the stream is empty
- Accumulator function: A binary operator that combines two values into one
Think of it like a running total: You start with an initial amount (identity), then process each element one by one, combining it with your running result.
How It Works
// Summing integers with identity 0
int sum = Stream.of(1, 2, 3, 4)
.reduce(0, (a, b) -> a + b);
// Result: 10
// Empty stream returns the identity
int emptySum = Stream.<Integer>empty()
.reduce(0, (a, b) -> a + b);
// Result: 0 (the identity value)
The identity must be the neutral element for your operation:
- For addition: identity = 0 (because 0 + x = x)
- For multiplication: identity = 1 (because 1 * x = x)
- For string concatenation: identity = "" (empty string)
Why the Identity Matters
// Product of numbers
int product = Stream.of(2, 3, 4)
.reduce(1, (a, b) -> a * b);
// Result: 24
// Finding maximum with a sensible default
int max = Stream.of(5, 2, 8, 1)
.reduce(Integer.MIN_VALUE, (a, b) -> a > b ? a : b);
// Result: 8
Notice this version returns T directly, not Optional<T>, because the identity guarantees you always have a result.
Key Takeaway: The identity-based reduce provides a safe default value for empty streams and always returns a concrete result rather than an Optional, making it ideal when you have a meaningful starting point for your reduction.