Java Stream Reduce
What Reduction Means
Reduction combines all the elements of a stream into a single result: a total, a maximum, a combined string, a summary object. Many terminal operations you've already seen are reductions — sum(), count(), max(), min(), average() — and reduce is the general operation they're all special cases of.
reduce repeatedly applies a combining function: it takes the result so far and the next element, and produces a new result so far.
reduce(0, (acc, x) -> acc + x) over [4, 1, 3, 2]
acc=0 x=4 -> 4
acc=4 x=1 -> 5
acc=5 x=3 -> 8
acc=8 x=2 -> 10 result: 10
There are three forms of reduce:
| Signature | Returns | Use when |
|---|---|---|
T reduce(T identity, BinaryOperator<T> accumulator) | T | There's a natural starting value (0 for sums, 1 for products, "", BigDecimal.ZERO) |
Optional<T> reduce(BinaryOperator<T> accumulator) | Optional<T> | There's no sensible starting value (max, min, "longest") — empty stream gives an empty Optional |
<U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner) | U | The result type differs from the element type |
Using reduce
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.*;
public class R1 {
public static void main(String[] args) {
List<Integer> qty = List.of(4, 1, 3, 2);
int total = qty.stream().reduce(0, (a, b) -> a + b);
int total2 = qty.stream().reduce(0, Integer::sum);
int product = qty.stream().reduce(1, (a, b) -> a * b);
Optional<Integer> max = qty.stream().reduce(Integer::max);
Optional<Integer> none = Stream.<Integer>empty().reduce(Integer::max);
System.out.println(total + " " + total2 + " " + product + " " + max.get() + " " + none.isPresent());
String sentence = Stream.of("Streams", "reduce", "values").reduce("", (a, b) -> a.isEmpty() ? b : a + " " + b);
System.out.println(sentence);
BigDecimal sum = Stream.of("12.50", "1899.00", "80.25").map(BigDecimal::new).reduce(BigDecimal.ZERO, BigDecimal::add);
System.out.println(sum);
int sumInt = qty.stream().mapToInt(Integer::intValue).sum();
OptionalInt maxInt = qty.stream().mapToInt(Integer::intValue).max();
System.out.println(sumInt + " " + maxInt.getAsInt() + " " + qty.stream().count());
}
}
Output:
10 10 24 4 false
Streams reduce values
1991.75
10 4 4
- Sum and product: the identity is the value that doesn't change the result —
0for addition,1for multiplication.Integer::sumis a method reference for the same addition. - Maximum without an identity:
reduce(Integer::max)returns anOptional, because an empty stream has no maximum. The empty stream's result is empty (isPresent()isfalse), rather than a made-up value. - Strings: reducing words into a sentence works, but each step creates a new
String, which is quadratic for long streams.Collectors.joining(" ")is the efficient way (Stream Collect lesson). BigDecimal:reduce(BigDecimal.ZERO, BigDecimal::add)is the standard way to total exact money values, sinceBigDecimalhas no primitive stream.- Built-in reductions: for numbers,
mapToInt(...).sum(),max(),average()andcount()are clearer and avoid boxing. Usereducewhen no specialised operation exists.
The Rules: Identity and Associativity
reduce is designed to work in parallel: the stream may be split into chunks, each chunk reduced separately (each starting from the identity), and the partial results combined. For that to give the same answer as sequential processing, two rules must hold:
- The identity must really be an identity:
accumulator(identity, x)must equalxfor everyx. - The function must be associative:
(a op b) op cmust equala op (b op c). Addition, multiplication,max,minand string concatenation are associative; subtraction and division are not.
Breaking either rule gives results that depend on how the stream was split:
import java.util.stream.*;
public class Wrong {
public static void main(String[] args) {
System.out.println("sequential sum, identity 10: " + IntStream.rangeClosed(1, 8).boxed().reduce(10, Integer::sum));
System.out.println("parallel sum, identity 10: " + IntStream.rangeClosed(1, 8).boxed().parallel().reduce(10, Integer::sum));
System.out.println("sequential subtraction: " + IntStream.rangeClosed(1, 8).boxed().reduce(0, (a, b) -> a - b));
System.out.println("parallel subtraction: " + IntStream.rangeClosed(1, 8).boxed().parallel().reduce(0, (a, b) -> a - b));
}
}
Output from one run on a two-core machine (the parallel results depend on the number of cores and how the work is split):
sequential sum, identity 10: 46
parallel sum, identity 10: 76
sequential subtraction: -36
parallel subtraction: 0
- Using
10as the "identity" to mean "start from 10" works sequentially (10 + 36 = 46), but in parallel every chunk adds its own 10. To add a starting value, reduce with the real identity and add the value afterwards:10 + stream.reduce(0, Integer::sum). - Subtraction isn't associative, so the parallel result is different from the sequential one.
Even if your code is sequential today, follow both rules — anyone can later add .parallel() or switch to parallelStream().
The Three-Argument Form
When the result type differs from the element type — summing the price × qty of Item objects into a double — the two-argument form doesn't fit, because its function must take and return the same type. The three-argument form separates the two jobs:
import java.util.*;
public class Three {
record Item(String name, double price, int qty) { }
public static void main(String[] args) {
List<Item> cart = List.of(new Item("pen", 12.5, 4), new Item("bag", 1899, 1), new Item("ink", 80, 2));
double total = cart.stream().reduce(0.0,
(sum, item) -> sum + item.price() * item.qty(),
Double::sum);
System.out.println(total);
System.out.println(cart.stream().mapToDouble(i -> i.price() * i.qty()).sum());
}
}
Output:
2109.0
2109.0
- The accumulator
(sum, item) -> ...adds oneItemto a runningDouble. - The combiner
Double::sumadds two partialDoubleresults together; it's used only when the stream runs in parallel. - The second line computes the same thing with
mapToDouble(...).sum(), which is simpler. In practice, map then reduce is usually clearer than the three-argument form; the three-argument form is mostly useful when mapping first isn't possible or would create many temporary objects.
reduce versus collect
reduce is for immutable results: each step creates a new value (a + b, a new BigDecimal, a new record). To accumulate into a mutable container — a List, a Map, a StringBuilder — use collect instead. A reduce that adds elements to an ArrayList breaks in parallel (all threads would modify the same list) and is inefficient sequentially. The Stream Collect lesson covers this "mutable reduction".
Step-by-Step Trace
To see exactly how a reduction proceeds, print inside the accumulator:
import java.util.stream.*;
public class Steps {
public static void main(String[] args) {
int result = Stream.of(4, 1, 3, 2).reduce(0, (acc, x) -> {
System.out.println(" acc=" + acc + " x=" + x + " -> " + (acc + x));
return acc + x;
});
System.out.println("result " + result);
}
}
Output:
acc=0 x=4 -> 4
acc=4 x=1 -> 5
acc=5 x=3 -> 8
acc=8 x=2 -> 10
result 10
The accumulator receives the result so far and the next element, exactly as a for loop with a running total would — but without a mutable variable outside the loop.
Practical Example: Order Statistics with a Combinable Summary
Dashboards show several figures about the same data at once: number of orders, revenue, average, largest order, first and last order time. Computing each with its own stream reads the data many times. A small summary record that knows how to combine itself can compute everything in one reduction — and, because combining is associative and there's a true identity, it works identically in parallel.
import java.time.*;
import java.util.*;
import java.util.stream.*;
public class Summary {
record Order(String id, String city, double amount, Instant placedAt) { }
record Stats(long count, double revenue, double largest, Instant first, Instant last) {
static final Stats EMPTY = new Stats(0, 0, 0, Instant.MAX, Instant.MIN);
static Stats of(Order o) {
return new Stats(1, o.amount(), o.amount(), o.placedAt(), o.placedAt());
}
Stats combine(Stats other) {
return new Stats(count + other.count, revenue + other.revenue,
Math.max(largest, other.largest),
first.isBefore(other.first) ? first : other.first,
last.isAfter(other.last) ? last : other.last);
}
double average() { return count == 0 ? 0 : revenue / count; }
}
public static void main(String[] args) {
Instant t = Instant.parse("2026-11-16T09:00:00Z");
List<Order> orders = new ArrayList<>();
Random rnd = new Random(42);
for (int i = 0; i < 10_000; i++) {
orders.add(new Order("O-" + i, i % 3 == 0 ? "Chennai" : "Madurai",
500 + rnd.nextInt(9_500), t.plusSeconds(rnd.nextInt(86_400))));
}
Stats seq = orders.stream().map(Stats::of).reduce(Stats.EMPTY, Stats::combine);
Stats par = orders.parallelStream().map(Stats::of).reduce(Stats.EMPTY, Stats::combine);
System.out.printf("orders %d, revenue %.0f, average %.2f, largest %.0f%n", seq.count(), seq.revenue(), seq.average(), seq.largest());
System.out.println("first " + seq.first() + ", last " + seq.last());
System.out.println("parallel result identical: " + seq.equals(par));
Stats chennai = orders.stream().filter(o -> o.city().equals("Chennai")).map(Stats::of).reduce(Stats.EMPTY, Stats::combine);
Stats none = orders.stream().filter(o -> o.city().equals("Salem")).map(Stats::of).reduce(Stats.EMPTY, Stats::combine);
System.out.printf("Chennai: %d orders, average %.2f; Salem: %d orders, average %.2f%n",
chennai.count(), chennai.average(), none.count(), none.average());
}
}
Output:
orders 10000, revenue 52513935, average 5251.39, largest 9999
first 2026-11-16T09:00:41Z, last 2026-11-17T08:59:48Z
parallel result identical: true
Chennai: 3334 orders, average 5250.60; Salem: 0 orders, average 0.00
How it works:
- Test data: 10,000 orders with random amounts and times, generated from a fixed seed so every run produces the same data.
Stats.of(order)turns one order into a summary of one: count 1, revenue and largest equal to its amount, first and last equal to its time.combinemerges two summaries: counts and revenues add up, the larger maximum wins, the earlier first time and later last time win. Every part is associative, so the order in which summaries are combined doesn't matter.Stats.EMPTYis a true identity: count 0, revenue 0, andInstant.MAX/Instant.MINas first/last, so any real time replaces them when combined. (Using0forlargestis an identity here because order amounts are never negative.)- One pass:
map(Stats::of).reduce(Stats.EMPTY, Stats::combine)computes all five figures together. The parallel version produces an identical record, confirming the rules hold. - Empty input: for a city with no orders, the reduction returns
EMPTY, andaverage()guards against dividing by zero.
This pattern — a small immutable summary type with an identity value and an associative combine method — is how statistics are aggregated in many systems, from IntSummaryStatistics in the JDK to metrics libraries and big-data frameworks (in functional-programming terms, it's a monoid).