Java 25 (LTS) reference · Stream API

Java Stream reduce() Method

Combine all elements into one value with an accumulator function, starting from an identity value.

Java 25 (LTS) Since Java 8

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

stream.reduce(identity, accumulator)

Parameters

ParameterDescription
identity
T
The starting value (0 for sums, 1 for products).
accumulator
BinaryOperator<T>
Combines a running result with the next element.

Return value

The combined value.

Examples

Sum and product
import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> nums = List.of(1, 2, 3, 4);
        System.out.println(nums.stream().reduce(0, Integer::sum));
        System.out.println(nums.stream().reduce(1, (a, b) -> a * b));
    }
}

Output

10
24

Run this on your computer — see “Get Started” for setup.

Without an identity: an Optional
import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        Optional<String> longest = Stream.of("tea", "kettle", "mug").reduce((a, b) -> a.length() >= b.length() ? a : b);
        System.out.println(longest.orElse("none"));
    }
}

Output

kettle

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 8Added

Was this page helpful?