What is the use of reduce() in Java 8 Streams?

reduce() is a general-purpose terminal Stream operation that folds all elements of a stream into a single result by repeatedly applying a binary operator, accumulating a running result as it processes each element.

Key Points: • The single-argument form reduce(BinaryOperator) returns an Optional<T>, since an empty stream has no result to produce. • The two-argument form reduce(identity, BinaryOperator) always returns a T, using the identity value as both the starting point and the fallback for an empty stream. • A three-argument overload adds a combiner function, needed when working with parallel streams where partial results must be merged. • Typical uses include summing, finding a maximum or minimum, string concatenation, or building up any custom aggregate. • For simple numeric aggregation, dedicated methods like sum(), max(), and min() on primitive streams are usually clearer and more efficient than a hand-written reduce().

Example: Given a list of prices, prices.stream().reduce(0.0, Double::sum) accumulates a running total starting at 0.0, effectively implementing a sum from scratch using reduce().

Code Example:

List<Integer> nums = Arrays.asList(4, 2, 9, 6);

Optional<Integer> max = nums.stream().reduce(Integer::max);
int total = nums.stream().reduce(0, Integer::sum);

System.out.println(max.get() + " " + total); // 9 15

Interview Tip: A concise interview answer is:

"reduce() combines all stream elements into a single value by repeatedly applying a binary operator to an accumulating result. I use the identity-argument form when I want a guaranteed default for an empty stream, and the no-identity form, which returns an Optional, when there's no sensible default. It's the general tool behind operations like sum, max, and min."