Java Stream Reduce

Su Suriya Ravichandran Updated 18 Nov 2026
8 min read ·Lesson 175 of 306

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:

SignatureReturnsUse when
T reduce(T identity, BinaryOperator<T> accumulator)TThere'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)UThe 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 — 0 for addition, 1 for multiplication. Integer::sum is a method reference for the same addition.
  • Maximum without an identity: reduce(Integer::max) returns an Optional, because an empty stream has no maximum. The empty stream's result is empty (isPresent() is false), 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, since BigDecimal has no primitive stream.
  • Built-in reductions: for numbers, mapToInt(...).sum(), max(), average() and count() are clearer and avoid boxing. Use reduce when 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:

  1. The identity must really be an identity: accumulator(identity, x) must equal x for every x.
  2. The function must be associative: (a op b) op c must equal a op (b op c). Addition, multiplication, max, min and 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 10 as 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 one Item to a running Double.
  • The combiner Double::sum adds two partial Double results 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:

  1. Test data: 10,000 orders with random amounts and times, generated from a fixed seed so every run produces the same data.
  2. 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.
  3. combine merges 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.
  4. Stats.EMPTY is a true identity: count 0, revenue 0, and Instant.MAX/Instant.MIN as first/last, so any real time replaces them when combined. (Using 0 for largest is an identity here because order amounts are never negative.)
  5. 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.
  6. Empty input: for a city with no orders, the reduction returns EMPTY, and average() 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).

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Stream Reduce and get answers drawn from it.

Signed-in readers only.