Skip to lesson

reduce with an identity

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

BillTotalDemo.javaJava
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));    }}
Output
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 rule sum + item. Integer::sum is a ready method that does the same addition.
  • With the identity form, reduce returns a plain int, not an Optional. 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). reduce states 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.

  1. Start: total is the identity, 0.
  2. First element 250: 0 + 250 gives 250.
  3. Second element 120: 250 + 120 gives 370.
  4. Third element 80: 370 + 80 gives 450.
  5. No elements left: reduce returns 450.
reduce(0, (total, x) -> total + x) over 250, 120 and 80. The running total starts at the identity 0, becomes 250 after the first element, 370 after the second and 450 after the third. 450 is the result.

Example 2 · Watching the accumulator step by step

ReduceTraceDemo.javaJava
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);    }}
Output
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 sum for 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.

import java.util.List;
public class ReduceTrace {
public static void main(String[] args) {
List<Integer> bill = List.of(250, 120, 80);
int result = bill.stream().reduce(0, (total, x) -> {
System.out.println(total + " + " + x);
return total + x;
});
System.out.println("Result: " + result);
}
}

Variables

None yet.

Output

(nothing printed yet)

Line 5The bill holds three amounts.

Step 1 of 9
On an empty stream the accumulator never runs, so 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

ReduceShapesDemo.javaJava
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);    }}
Output
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_VALUE for Math::max. Combining the identity with any value gives that value back.
  • The product uses Long values and 1L, 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()

ReduceVsSumDemo.javaJava
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);    }}
Output
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 a Stream<Integer>, so every amount is boxed into an Integer object; mapToInt(...) makes an IntStream of plain int values with a ready sum().
  • For totals, prefer mapToInt(...).sum(): it is shorter, faster and cannot get the identity wrong. Keep reduce for 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

WrongIdentityDemo.javaJava
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);    }}
Output
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 x give back x? 0 + x and 1 * x do; 1 + x and 0 * x do 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 4

Next step

Check your understanding

11 quick questions