reduce() is a general-purpose terminal Stream operation that combines all elements into a single result using an identity value and an accumulator function.
Key Points: • reduce(identity, accumulator) starts with the identity value and repeatedly applies the accumulator to fold in each stream element. • For summing integers, reduce(0, Integer::sum) uses 0 as the identity since adding 0 doesn't change a value. • reduce() without an identity returns an Optional<T>, since an empty stream has no meaningful result to return. • It's more general than specialized terminal operations like sum() or max(), since the accumulator can express arbitrary combining logic. • On parallel streams, reduce() requires the accumulator to be associative for correct, deterministic results.
Example: Given the list [1, 2, 3, 4], calling reduce(0, Integer::sum) folds the elements together starting from 0, producing a total of 10.
Code Example:
int total = numbers.stream()
.reduce(0, Integer::sum);Interview Tip: A concise interview answer is:
"reduce(identity, accumulator) folds a stream down to a single value, starting from the identity and combining elements one at a time with the accumulator function. For summing integers, reduce(0, Integer::sum) is equivalent to using an IntStream's sum(), just more general-purpose."