reduce with an identity
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)reduce combines all the elements of a stream into one value, two at a time. You give it a starting value, the identity, and a rule for combining, the accumulator: reduce(0, (total, x) -> total + x) adds up every element.
Many values into one
Reduction combines all elements of a stream into one result, such as a sum or a maximum, by applying an operation again and again.
A reduction turns many values into one: the total of a bill, the product of some numbers, the longest name in a class. count, min and max are reductions with a fixed rule. reduce lets you write the rule yourself.
Example 1 · The total of a bill: loop, then reduce
import java.util.List;
public class BillTotalDemo { public static void main(String[] args) { List<Integer> bill = List.of(250, 120, 80);
// old way: a running total int loopTotal = 0; for (int item : bill) { loopTotal = loopTotal + item; } System.out.println("Loop total: " + loopTotal);
int total = bill.stream().reduce(0, (sum, item) -> sum + item); System.out.println("reduce total: " + total);
int sameTotal = bill.stream().reduce(0, Integer::sum); System.out.println("Integer::sum total: " + sameTotal);
List<Integer> emptyCart = List.of(); System.out.println("Empty cart total: " + emptyCart.stream().reduce(0, Integer::sum)); }}Loop total: 450 reduce total: 450 Integer::sum total: 450 Empty cart total: 0
What this code does
reduce(0, (sum, item) -> sum + item)has the same two parts as the loop: the starting value 0 and the rulesum + item.Integer::sumis a ready method that does the same addition.- With the identity form,
reducereturns a plainint, not anOptional. For an empty cart it simply returns the identity, 0. - Why reduce: the loop mixes the idea (add everything) with the bookkeeping (a variable and its update).
reducestates the idea once, and the same call works unchanged on a parallel stream.
The old way is a loop with a running result: int total = 0; for (int x : bill) total = total + x;. It has two parts: a starting value (0) and a rule that combines the result so far with the next element (total + x). reduce(identity, accumulator) takes exactly those two parts. The identity is the starting value. The accumulator is a BinaryOperator<T>: a function that takes two values of the same type and returns one, such as (a, b) -> a + b or the method reference Integer::sum.
Identity and accumulator, traced step by step
Take a shop bill List.of(250, 120, 80) and reduce(0, (total, x) -> total + x). total is the result so far; x is the next element.
- Start:
totalis the identity, 0. - First element 250:
0 + 250gives 250. - Second element 120:
250 + 120gives 370. - Third element 80:
370 + 80gives 450. - No elements left:
reducereturns 450.
Example 2 · Watching the accumulator step by step
import java.util.List;
public class ReduceTraceDemo { public static void main(String[] args) { List<Integer> bill = List.of(250, 120, 80);
int total = bill.stream().reduce(0, (sum, item) -> { int next = sum + item; System.out.println("sum " + sum + " + item " + item + " = " + next); return next; }); System.out.println("Final: " + total); }}sum 0 + item 250 = 250 sum 250 + item 120 = 370 sum 370 + item 80 = 450 Final: 450
What this code does
- The accumulator's first parameter is the result so far; the second is the next element. The first call gets the identity 0 as the result so far.
- Each call's return value becomes
sumfor the next call. The printing is only for learning; real accumulators should just compute and return.
Trace the code
Watch reduce carry the total
Step through the program and watch total and x change.
Variables
None yet.
Output
(nothing printed yet)Line 5The bill holds three amounts.
reduce returns the identity itself: an empty cart totals 0.reduce versus sum for numbers
For adding numbers there is a shorter way: mapToInt(Order::amount).sum(). mapToInt turns the stream into an IntStream, a stream of plain int values, which has a ready sum(). It reads like the task and avoids boxing each number into an Integer.
Example 3 · Product, longest name and the highest mark
import java.util.List;
public class ReduceShapesDemo { public static void main(String[] args) { // ways to choose a 4-digit PIN with no repeated digit: 10 * 9 * 8 * 7 List<Long> choices = List.of(10L, 9L, 8L, 7L); long pins = choices.stream().reduce(1L, (a, b) -> a * b); System.out.println("PINs without repeats: " + pins);
List<String> names = List.of("Ira", "Siddharth", "Kavya", "Raghavendra", "Om"); String longest = names.stream() .reduce("", (best, n) -> n.length() > best.length() ? n : best); System.out.println("Longest name: " + longest);
List<Integer> marks = List.of(67, 92, 45, 88); int highest = marks.stream().reduce(Integer.MIN_VALUE, Math::max); System.out.println("Highest mark: " + highest); }}PINs without repeats: 5040 Longest name: Raghavendra Highest mark: 92
What this code does
- Each reduction has its own neutral identity: 1 for a product, the empty String for "longer name", and
Integer.MIN_VALUEforMath::max. Combining the identity with any value gives that value back. - The product uses
Longvalues and1L, so a long chain of multiplication has room to grow.n.length() > best.length()uses>, so on a tie the earlier name stays.
Example 4 · reduce versus mapToInt().sum()
import java.util.List;
record Order(String item, int qty, int price) {}
public class ReduceVsSumDemo { public static void main(String[] args) { List<Order> orders = List.of( new Order("Notebook", 4, 60), new Order("Pen", 10, 15), new Order("Calculator", 1, 750));
int byReduce = orders.stream() .map(o -> o.qty() * o.price()) .reduce(0, Integer::sum);
int bySum = orders.stream() .mapToInt(o -> o.qty() * o.price()) .sum();
int itemsCount = orders.stream() .mapToInt(Order::qty) .sum();
System.out.println("Total by reduce: Rs. " + byReduce); System.out.println("Total by sum: Rs. " + bySum); System.out.println("Items bought: " + itemsCount); }}Total by reduce: Rs. 1140 Total by sum: Rs. 1140 Items bought: 15
What this code does
- Both give 240 + 150 + 750 = 1140.
map(...)makes aStream<Integer>, so every amount is boxed into anIntegerobject;mapToInt(...)makes anIntStreamof plainintvalues with a readysum(). - For totals, prefer
mapToInt(...).sum(): it is shorter, faster and cannot get the identity wrong. Keepreducefor rules that have no ready method.
The Primitive and Parallel Streams module covers IntStream fully. Use reduce when there is no ready method: a product, the longest name, combining discounts, or any rule of your own. Watch the type, too. A product grows fast, so int overflows; reduce long values with the identity 1L instead.
For joining Strings, reduce("", String::concat) works but builds a new String at every step. Collectors.joining, covered in the Stream Collectors module, is the right tool.
Trap: an identity that is not neutral
The identity must be neutral for the accumulator: combining it with any value x must give back x unchanged. For + that value is 0, because 0 + x is x. For * it is 1.
Example 5 · Trap: an identity that is not neutral
import java.util.List;
public class WrongIdentityDemo { public static void main(String[] args) { List<Integer> marks = List.of(70, 85, 90);
int wrongSum = marks.stream().reduce(1, Integer::sum); System.out.println("Sum with identity 1: " + wrongSum);
int wrongProduct = marks.stream().reduce(0, (a, b) -> a * b); System.out.println("Product with identity 0: " + wrongProduct);
int rightSum = marks.stream().reduce(0, Integer::sum); long rightProduct = marks.stream() .map(m -> (long) m) .reduce(1L, (a, b) -> a * b); System.out.println("Sum with identity 0: " + rightSum); System.out.println("Product with identity 1: " + rightProduct); }}Sum with identity 1: 246 Product with identity 0: 0 Sum with identity 0: 245 Product with identity 1: 535500
What this code does
- With identity 1, the sum starts one too high and the report shows 246 instead of 245. With identity 0, every product is 0 from the first step. Neither line throws an error, so the bug can reach the marksheet.
- Check the identity with one question: does combining it with any
xgive backx?0 + xand1 * xdo;1 + xand0 * xdo not.
For "longer of two names" it is the empty String "". For Math::max it is Integer.MIN_VALUE. A wrong identity does not crash; it just gives a wrong answer. reduce(1, Integer::sum) returns the total plus 1. reduce(0, (a, b) -> a * b) always returns 0.
It gets worse on a parallel stream, where each chunk starts from the identity. With 1 as the identity of a sum, the answer is off by the number of chunks, which can change from one computer to another. A neutral identity gives the same answer everywhere.
Find the bug
Find the wrong identity
Click the line whose starting value is not neutral.
The bill 250, 120, 80 should print 450, but it prints 455.
Round 1 of 4Next step
Check your understanding
11 quick questions