Java

Stream.reduce — Aggregate to a Single Value

admin by @admin ADMIN
Jun 18, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`reduce` collapses a stream to one value: sum, product, max, min, custom accumulation. Two-arg form needs an identity (zero/seed); three-arg form supports parallel streams via a combiner.
Java
Raw
import java.util.*;
import java.util.stream.*;

class Demo {
    void example() {
        var nums = List.of(1, 2, 3, 4, 5);

        // With identity — never returns Optional
        int sum     = nums.stream().reduce(0, Integer::sum);
        int product = nums.stream().reduce(1, (a, b) -> a * b);
        int max     = nums.stream().reduce(Integer.MIN_VALUE, Integer::max);
        System.out.printf("sum=%d product=%d max=%d%n", sum, product, max);

        // Without identity — returns Optional (empty stream → empty)
        Optional<Integer> maybeMax = nums.stream().reduce(Integer::max);
        maybeMax.ifPresent(System.out::println);

        // Three-arg parallel reduce — identity, accumulator, combiner
        int parallelSum = nums.parallelStream()
            .reduce(0, Integer::sum, Integer::sum);
        System.out.println(parallelSum);

        // String concat — but prefer Collectors.joining for this
        String joined = List.of("a", "b", "c").stream()
            .reduce("", (acc, s) -> acc + s);
        System.out.println(joined);             // abc
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.