Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java Stream Reduce: Syntax, Behavior, and Pitfalls

Understand Java Stream.reduce overloads, accumulator behavior, identity requirements, parallel execution, and when to use collect for mutable results.

~5 min readJava
#Java Streams#Functional Programming#Stream API#Java 8
Illustration of a Java stream pipeline with multiple distinct elements converging into a single result through the reduce operation.

The reduce operation is a terminal method on the Java Stream API that folds all elements into a single value. This article explains the overloads of reduce, how the accumulator works, which identity values are valid, how parallel streams affect results, and when collect is a better fit.

The Three Overloads of reduce

The generic Stream<T> interface defines three overloads of reduce:

java
Optional<T> reduce(BinaryOperator<T> accumulator) T reduce(T identity, BinaryOperator<T> accumulator) <U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner)

The first overload returns Optional<T> because an empty stream has no value to fall back on. The second and third overloads return a concrete value because the identity provides the default when no elements exist.

The single-argument version is the one most developers encounter first, but the two-argument version is usually safer when a natural identity value exists.

How the Accumulator Applies to Each Element

In the two-argument overload, the accumulator is a BinaryOperator<T> that takes two values and produces one. For a sequential stream, the runtime applies it from left to right:

java
List<Integer> numbers = List.of(2, 4, 6, 8); int sum = numbers.stream() .reduce(0, (a, b) -> a + b);

The evaluation proceeds as follows: the identity 0 is combined with 2 to produce 2, then 2 is combined with 4 to produce 6, then 6 with 6 to produce 12, and finally 12 with 8 to produce 20.

The same logic applies to any associative operation. Concatenating strings is a common example:

java
List<String> words = List.of("stream", "reduce", "example"); String joined = words.stream() .reduce("", (a, b) -> a + b);

The result is "streamreduceexample". This approach creates a new String for every combination step, which is why Collectors.joining() is usually a better choice for string concatenation.

Why the Identity Value Must Be a True Identity

The identity value is not just a fallback for an empty stream. In the two-argument overload, it participates in every accumulation step, and in parallel execution it seeds each partial result. If the identity is not a true identity for the accumulator operation, the result will be wrong.

For addition, 0 is valid because x + 0 == x. For multiplication, 1 is valid because x * 1 == x. Using 0 as the identity for multiplication makes every result 0:

java
int product = List.of(2, 3, 4).stream() .reduce(0, (a, b) -> a * b); // Result: 0, not 24

A common bug is using 0 as the identity for multiplication. For the two-argument overload, the identity must satisfy accumulator.apply(identity, element) == element for every element in the stream. For the three-argument overload, the requirement is slightly different: the identity must be an identity for the combiner, and the combiner must be compatible with the accumulator.

Parallel Streams and the Combiner

When a stream runs in parallel, the runtime splits the elements into chunks, applies the accumulator within each chunk, and then combines the partial results. For the two-argument overload, the accumulator itself is used as the combiner. For the three-argument overload, the third parameter is the combiner.

This is where non-associative operations break. The accumulator used with the two-argument overload must be associative: f(f(a, b), c) == f(a, f(b, c)). Subtraction is not associative:

java
int result = List.of(10, 3, 2).parallelStream() .reduce(0, (a, b) -> a - b);

A sequential run produces 0 - 10 - 3 - 2 = -15. A parallel run may combine chunks differently and produce a different value. The result depends on how the stream is split, which makes it nondeterministic.

The three-argument overload exists for cases where the accumulator type differs from the element type. A common example is reducing strings into an integer length:

java
List<String> words = List.of("stream", "reduce", "example"); int totalLength = words.parallelStream() .reduce(0, (len, word) -> len + word.length(), Integer::sum);

Here the accumulator converts each word to its length and adds it to the running total, while the combiner merges partial totals. The identity 0 is valid because it is an identity for Integer::sum. The combiner must also be compatible with the accumulator: if a parallel reduction splits the stream, combining partial totals must produce the same result as reducing the whole stream sequentially.

When reduce Is the Wrong Choice

The reduce operation is designed for immutable reduction: each step produces a new value. It is not suitable for accumulating into a mutable container. Consider this code:

java
List<String> collected = stream.reduce( new ArrayList<>(), (list, element) -> { list.add(element); return list; }, (left, right) -> { left.addAll(right); return left; });

In a sequential stream this works, but in a parallel stream multiple threads share the same ArrayList instance, and add is not thread-safe. The result can be corrupted or fail unpredictably. The correct approach for mutable accumulation is collect:

java
List<String> collected = stream.collect(Collectors.toList());

The collect method is specifically designed for mutable reduction and handles parallel execution correctly by creating separate containers per chunk and merging them at the end. Use reduce when the result is a single immutable value, and collect when the result is a collection or a mutable object.

Performance Characteristics

Each call to the accumulator returns a new value. When a generic Stream<Integer> is built from primitive values, each element is boxed and the accumulator returns a new Integer result, adding allocation overhead. If performance matters and the stream contains primitive values, prefer IntStream, LongStream, or DoubleStream and their specialized reduce or sum methods:

java
int sum = IntStream.of(2, 4, 6, 8).sum();

These specialized streams avoid boxing and are usually cheaper for large inputs.

For large collections, parallel streams can reduce wall-clock time, but only when the accumulator is cheap relative to the splitting overhead. A simple addition over a small list is often slower in parallel because the cost of splitting and combining outweighs the benefit. Measure with realistic data before enabling parallelStream().

Edge Cases That Produce Surprising Results

The single-argument reduce returns an empty Optional when the stream has no elements. This is easy to forget when the stream comes from a filter:

java
Optional<Integer> max = numbers.stream() .filter(n -> n > 100) .reduce(Integer::max);

If no element passes the filter, the result is Optional.empty(). The two-argument version avoids this by returning the identity, which is why it is often preferable when a sensible default exists.

Another edge case is the empty stream with the two-argument version. It returns the identity directly without invoking the accumulator, which is correct but worth remembering when the identity has side effects. The accumulator should never have side effects, because parallel execution can invoke it concurrently and does not guarantee the order in which elements are combined.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.