Video in progress
How does reduce() work, and why is the identity value needed?
reduce folds the elements into one result: it starts from the identity and combines each element into the previous result with an accumulator. The identity is the starting value that is returned for an empty stream and doesn't distort the result.
📖 Answer
List<Integer> nums = List.of(3, 5, 7);
int sum = nums.stream().reduce(0, Integer::sum); // 15
int product = nums.stream().reduce(1, (a, b) -> a * b); // 105
Optional<Integer> max = nums.stream().reduce(Integer::max); // Optional[7]
There are three variants:
reduce(identity, accumulator): there's always a result, and for an empty stream it is theidentity;reduce(accumulator): there's no identity, so it returns anOptional;reduce(identity, accumulator, combiner): for when the result type differs from the element type, or for a parallel stream.
A mistake when picking the identity:
int sum = nums.stream().reduce(10, Integer::sum);
On a sequential stream you get 25, but on a parallel one the 10 is added to every chunk and you can get a different number. The identity's condition: identity op x == x. 0 for addition, 1 for multiplication.
In practice, mapToInt(...).sum() for sums, max(...) for the largest, and joining for strings are easier to read. Use reduce when those aren't enough.
Sign up to mark studied questions and save your progress.