Java Stream reduce: Identity, Accumulator, Combiner and Three-Argument collect
Master Java's Stream.reduce in its three forms: reduce with an Optional result, with an identity value, and with an accumulator and combiner. Learn why the operation must be associative, what a wrong identity does in parallel, and when to use the three-argument collect instead.
kvi5hnuCode Sprout team member8 min readOn this page
count, max and min are special cases of a more general idea: combining all elements of a stream into one value, step by step. The reduce method lets you specify that combining step yourself. For mathematical operations especially, a reduction is much easier to write than a custom collector. This article covers the three forms of reduce, the rules that make them work in parallel, and the three-argument collect for when you need a mutable result.
reduce with a binary operator
The simplest form takes a function that combines two values into one, and keeps applying it, starting with the first two elements:
List<Integer> values = ...;
Optional<Integer> sum = values.stream().reduce((x, y) -> x + y);
The result is v₀ + v₁ + v₂ + … where the vᵢ are the elements. reduce(Integer::sum) says the same thing more briefly. The method returns an Optional because an empty stream has no meaningful result. A one-element stream simply returns that element.
In general, if op is the operation, the reduction computes v₀ op v₁ op v₂ op …. Many operations fit this pattern: sum, product, maximum and minimum, string concatenation, set union and intersection, BigInteger multiplication and so on.
Associativity
To be usable with parallel streams, the operation must be associative: it mustn't matter how the elements are grouped. In symbols, (x op y) op z must equal x op (y op z). A parallel stream reduces each chunk separately and then combines the partial results, which regroups the computation, so only associative operations give the same answer.
Addition, multiplication, max, min and concatenation are associative. Subtraction is not: (6 − 3) − 2 = 1, but 6 − (3 − 2) = 5. The demo shows a parallel subtraction "reduction" giving a different result from the sequential one. Floating-point addition is nearly associative, since rounding can make a parallel double sum differ in the last digits.
Associativity doesn't mean commutativity. Concatenation is associative but "a" + "b" isn't "b" + "a". That's fine, because a parallel stream keeps chunks in encounter order when combining them.
reduce with an identity
Often an operation has an identity value e such that e op x = x for every x: 0 for addition, 1 for multiplication, the empty string for concatenation. Pass it as the first argument and you get a plain result instead of an Optional:
Integer sum = values.stream().reduce(0, (x, y) -> x + y);
// computes 0 + v0 + v1 + v2 + ...
For an empty stream, the identity is returned.
The identity must really be an identity. A parallel stream starts every chunk with it, so it may be used many times. With reduce(10, Integer::sum), a sequential stream adds 10 once, but a parallel stream adds it once per chunk, and the result depends on how the stream was split. To add a constant, add it after the reduction.
reduce with an accumulator and a combiner
Now suppose you want the total length of a stream of strings. The forms above need a function of type (T, T) -> T, with one type for both operands and the result. Here there are two types: the elements are Strings and the running total is an int.
The third form handles this. You provide an accumulator that folds one element into a running total, and a combiner that adds up the totals of separately processed chunks:
int result = words.reduce(0,
(total, word) -> total + word.length(), // accumulator: (U, T) -> U
(total1, total2) -> total1 + total2); // combiner: (U, U) -> U
The combiner is used only for parallel streams, but you must always supply it, and it must be compatible with the accumulator. Combining a partial total with the accumulation of one element must equal accumulating that element directly: combiner(u, accumulator(identity, t)) must equal accumulator(u, t).
Mutable reduction: the three-argument collect
reduce is designed for immutable values: each step returns a new value. Sometimes you want to accumulate into a mutable object instead, such as a BitSet or a StringBuilder. reduce doesn't fit. In parallel, you can't let all threads modify one BitSet because it isn't thread-safe, and reduce allows only a single identity object, while each chunk needs its own empty container.
That's what the three-argument collect is for. You give it the functions a collector is made of (article 12) directly, without a finisher:
- a supplier that makes a new container,
- an accumulator that adds one element to a container,
- a combiner that merges the second container into the first.
BitSet result = stream.collect(BitSet::new, BitSet::set, BitSet::or);
The accumulator is a BiConsumer, as in Collector, but unlike in Collector the combiner is a BiConsumer too. Both modify their first argument and return nothing, which is why existing methods such as BitSet::or and StringBuilder::append fit directly.
A complete example
import java.math.BigInteger;
import java.util.*;
import java.util.stream.*;
public class Solution {
public static void main(String[] args) {
List<Integer> values = List.of(3, 1, 4, 1, 5, 9, 2, 6);
// one argument: Optional result
Optional<Integer> sum = values.stream().reduce((x, y) -> x + y);
System.out.println("sum: " + sum);
System.out.println("sum of nothing: " + Stream.<Integer>empty().reduce(Integer::sum));
// two arguments: identity, no Optional
int total = values.stream().reduce(0, Integer::sum);
System.out.println("sum with identity: " + total);
System.out.println("empty with identity: " + Stream.<Integer>empty().reduce(0, Integer::sum));
System.out.println("product: " + values.stream().reduce(1, (x, y) -> x * y));
System.out.println("max: " + values.stream().reduce(Integer::max).orElseThrow());
System.out.println("factorial of 25: "
+ IntStream.rangeClosed(1, 25).mapToObj(BigInteger::valueOf).reduce(BigInteger.ONE, BigInteger::multiply));
// subtraction isn't associative: sequential and parallel disagree
List<Integer> numbers = IntStream.rangeClosed(1, 100).boxed().toList();
int seqDiff = numbers.stream().reduce(0, (x, y) -> x - y);
int parDiff = numbers.parallelStream().reduce(0, (x, y) -> x - y);
System.out.println("subtraction, sequential: " + seqDiff + ", parallel matches: " + (seqDiff == parDiff));
// a wrong identity is counted once per chunk in parallel
int seq = numbers.stream().reduce(10, Integer::sum);
int par = numbers.parallelStream().reduce(10, Integer::sum);
System.out.println("identity 10, sequential: " + seq + ", parallel adds it more than once: " + (par > seq));
// three arguments: the result type differs from the element type
List<String> words = List.of("reduce", "is", "a", "general", "mechanism");
int totalLength = words.parallelStream().reduce(0,
(subtotal, word) -> subtotal + word.length(), // accumulator
Integer::sum); // combiner
System.out.println("total length: " + totalLength);
System.out.println("simpler: " + words.stream().mapToInt(String::length).sum());
// string concatenation is associative but slow with reduce
System.out.println("concatenated: " + words.stream().reduce("", String::concat));
System.out.println("joined: " + String.join("", words));
// mutable reduction with three-argument collect
BitSet bits = IntStream.of(1, 3, 5, 7, 3, 64).boxed().parallel()
.collect(BitSet::new, BitSet::set, BitSet::or);
System.out.println("bit set: " + bits);
StringBuilder sb = words.stream().collect(StringBuilder::new,
(b, w) -> b.append(w.charAt(0)), StringBuilder::append);
System.out.println("initials: " + sb);
// collect into an ArrayList the long way
ArrayList<String> list = words.parallelStream().collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
System.out.println("list keeps order: " + list.equals(words));
}
}
sum: Optional[31]
sum of nothing: Optional.empty
sum with identity: 31
empty with identity: 0
product: 6480
max: 9
factorial of 25: 15511210043330985984000000
subtraction, sequential: -5050, parallel matches: false
identity 10, sequential: 5060, parallel adds it more than once: true
total length: 25
simpler: 25
concatenated: reduceisageneralmechanism
joined: reduceisageneralmechanism
bit set: {1, 3, 5, 7, 64}
initials: riagm
list keeps order: true
The parallel results are compared rather than printed, because their exact values depend on how many chunks the stream is split into, which varies between machines.
Common questions
What is the difference between reduce and collect?
reduce combines immutable values: every step returns a new value, as in Integer::sum or BigInteger::multiply. collect accumulates into a mutable container, such as a list, a StringBuilder or a map, with one container per parallel chunk. Using reduce with a mutable object as the identity is a classic bug: every chunk modifies the same shared object.
How do I sum BigDecimal values?
amounts.stream().reduce(BigDecimal.ZERO, BigDecimal::add). Zero is a true identity for addition and add is associative, so this is correct in parallel too, and it has no rounding errors.
How do I find the record with the largest value using reduce?
reduce(BinaryOperator.maxBy(Comparator.comparing(City::population))). But max(comparing(City::population)) says the same thing more directly.
Why is reduce(0, Integer::sum) slower than mapToInt(...).sum()?
Stream<Integer> holds boxed Integer objects, and each step unboxes two values and boxes the result. An IntStream works on primitive int values without allocating anything.
Can a reduction overflow?
Yes. reduce(0, Integer::sum) wraps around silently past Integer.MAX_VALUE. Use mapToLong(...).sum(), Math::addExact (which throws on overflow), or BigInteger/BigDecimal for unbounded values.
API reference
java.util.stream.Stream<T>
| Method | Description |
|---|---|
Optional<T> reduce(BinaryOperator<T> accumulator) | combines the elements with accumulator; empty Optional for an empty stream |
T reduce(T identity, BinaryOperator<T> accumulator) | starts from identity, which is also the result for an empty stream |
<U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner) | accumulates elements into a result of another type; combiner merges results of chunks |
<R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner) | mutable reduction: each chunk fills its own container from supplier, and combiner merges the second container into the first |
Summary
reduce(op)combines all elements with a binary operation and returns anOptional.reduce(identity, op)starts from an identity value and returns it for an empty stream. The identity is used once per parallel chunk, so it must be a true identity.- The operation must be associative for parallel streams. Subtraction isn't, and floating-point addition only approximately is.
reduce(identity, accumulator, combiner)handles a result type different from the element type, but mapping to a primitive stream is usually simpler.- For mutable results such as
BitSetorStringBuilder, usecollect(supplier, accumulator, combiner).
Practice Questions
Why does reduce(Integer::sum) return Optional<Integer> but reduce(0, Integer::sum) return Integer?
Without an identity, an empty stream has no value to return, so the result is wrapped in an Optional. With an identity, the empty stream simply returns the identity, 0.
Is (x, y) -> x * 2 + y associative? What would happen if you used it in a parallel reduce?
No. Grouping as (x op y) op z gives 4x + 2y + z, while x op (y op z) gives 2x + 2y + z. A parallel reduction would group the elements differently from a sequential one and give a different, unpredictable result.
A colleague writes values.parallelStream().reduce(100, Integer::sum) to add 100 to the total. What's wrong?
100 isn't an identity for addition. Each parallel chunk starts from 100, so it's added several times, and the result depends on the number of chunks. Write values.parallelStream().reduce(0, Integer::sum) + 100 instead.
Compute the product of the numbers 1 to 30 exactly, using a stream.
LongStream.rangeClosed(1, 30).mapToObj(BigInteger::valueOf).reduce(BigInteger.ONE, BigInteger::multiply). A long would overflow, and BigInteger multiplication is associative with identity ONE.
Why can't you reduce into a single shared BitSet, and what do you use instead?
reduce is meant for immutable values, with one identity object shared by all chunks. Modifying one BitSet from several threads isn't safe. Use collect(BitSet::new, BitSet::set, BitSet::or), which gives each chunk its own BitSet and merges them afterwards.
Previous: Implementing Custom Java Collectors with Collector.of
Next: Java Stream Gatherers: windowFixed, windowSliding, fold, scan and mapConcurrent
Related reading
- Implementing Custom Java Collectors with Collector.of
- Java Downstream Collectors: counting, mapping, filtering, teeing and More
- Java groupingBy and partitioningBy: Grouping Stream Elements
- Java Map Views and Special Maps: LinkedHashMap, EnumMap, WeakHashMap and IdentityHashMap
- Java Lambda Variable Scope, Processing Lambdas and Comparator Methods

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.