Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java Stream reduce vs collect: Key Differences

Understand the key differences between Java Stream reduce and collect, including how each terminal operation works and when to choose one over the other.

~4 min readJava
#Java Streams#reduce#collect#terminal operations
A visual comparison of Java Stream reduce and collect terminal operations.

The Decision Between reduce and collect

When working with Java streams, both reduce and collect are terminal operations that produce a result from the stream's elements. At first glance they can seem interchangeable, but they are designed for different kinds of reductions. The choice between them affects code clarity, correctness, and how easily the operation can be parallelized.

reduce performs an immutable reduction: it combines stream elements into a single value using a binary operator, without relying on modifying external state. collect performs a mutable reduction: it accumulates elements into a mutable container, such as a List, Map, or StringBuilder, and then optionally transforms that container.

Understanding this distinction is the first step in choosing the right operation for your use case.

How reduce Works

The reduce method has three overloads. The first takes a BinaryOperator<T> and returns an Optional<T>:

java
List<Integer> numbers = List.of(1, 2, 3, 4, 5); Optional<Integer> sum = numbers.stream().reduce(Integer::sum);

The second overload takes an identity value and a BinaryOperator<T>:

java
int sum = numbers.stream().reduce(0, Integer::sum);

The third overload takes an identity, a BiFunction accumulator, and a BinaryOperator combiner. You need it when the result type differs from the element type, or when you want a parallel-friendly way to combine partial results into a different type.

Because the intended use of reduce is to combine immutable values, each step creates a new result. When the binary operator is associative, this is safe for parallel execution because partial results can be combined independently. Trying to build a collection with reduce is also inefficient: each step would have to create a new collection that includes the previous elements.

How collect Works

The collect method is designed for mutable reduction. It takes a Collector that defines how to create a mutable container, how to add each element to it, and how to combine two containers in parallel.

The most common collectors are provided by the Collectors utility class:

java
List<String> names = people.stream() .map(Person::getName) .collect(Collectors.toList()); Map<String, List<Person>> byCity = people.stream() .collect(Collectors.groupingBy(Person::getCity)); String joined = names.stream().collect(Collectors.joining(", "));

collect is the right choice when the result is a collection or a complex object that can be built incrementally. The mutable container is updated in place, avoiding the repeated copying that would occur with reduce.

When to Use reduce

Use reduce when you want to produce a single immutable value from a stream, such as a sum, product, maximum, or minimum. The binary operator should be associative because that is required for parallel reduction.

java
int product = numbers.stream().reduce(1, (a, b) -> a * b);

You can also use reduce to implement custom aggregation logic that does not have a matching collector, as long as the operation is associative and the identity value is correct.

Avoid using reduce to build collections or mutable objects. The following code is a common anti-pattern:

java
List<String> result = Stream.of("a", "b") .reduce(new ArrayList<>(), (list, element) -> { list.add(element); return list; }, (list1, list2) -> { list1.addAll(list2); return list1; });

This mutates the accumulator list, which violates the contract of reduce and can produce incorrect results when the stream is parallelized. Use collect when the target is a mutable container.

When to Use collect

Use collect whenever the result is a mutable container or a value that can be built by accumulating elements. This includes lists, sets, maps, strings, and custom objects.

collect is also more flexible because collectors can be composed. For example, you can use Collectors.groupingBy with a downstream collector to produce a nested structure:

java
Map<String, Long> countByCity = people.stream() .collect(Collectors.groupingBy(Person::getCity, Collectors.counting()));

The Collectors class provides many ready-made collectors, and you can create custom collectors with Collector.of when you need specific behavior.

Performance and Parallelism Considerations

Both reduce and collect can be parallelized, but they have different requirements.

reduce is inherently parallel-friendly when the binary operator is associative, because the stream can split the input, compute partial results in parallel, and combine those results. This works well for numeric operations and other associative functions.

collect also supports parallelism, but it requires that the collector's combiner correctly merges two containers. Many built-in collectors are designed for this, but custom collectors need care.

In sequential streams, the performance difference is usually negligible. Choose the operation based on the shape of the result you need, not on micro-optimizations. Using reduce to build a collection will be slower than collect because of the repeated copying.

Common Pitfalls

One common mistake is using reduce with a non-associative function. For example, subtraction is not associative, so a parallel stream may produce a different result from a sequential stream.

Another pitfall is using a mutable object as the identity value in reduce. The identity must be an actual identity element for the binary operator, and it should not be modified during the reduction.

With collect, a frequent issue is writing a custom Collector whose combiner does not correctly merge two containers. In a parallel stream, an incorrect combiner can lose or duplicate data. Built-in collectors such as Collectors.toList() and Collectors.groupingBy are designed to be combined, so you only need to verify this when writing custom collectors.

Custom Collectors and Advanced Usage

When the built-in collectors are not enough, you can create a custom collector using Collector.of. This lets you define the supplier, accumulator, combiner, and finisher.

java
Collector<Person, StringBuilder, String> nameCollector = Collector.of( StringBuilder::new, (sb, person) -> sb.append(person.getName()).append(", "), (left, right) -> left.append(right), sb -> sb.toString() );

This gives you full control over the reduction process and is often clearer than a complex reduce chain.

In summary, reduce is for immutable reduction, collect is for mutable reduction. Choose the one that matches the shape of your result and the semantics of your operation.

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.