Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Stream.reduce: practical reference

Stream.reduce: practical reference: Stream.reduce performs a terminal associative reduction: an identity overload returns the identity for an empty stream, while the overload without it returns Optional.empty().

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

Stream.reduce(...)

Stream.reduce performs a terminal associative reduction: an identity overload returns the identity for an empty stream, while the overload without it returns Optional.empty().

Use reduce for immutable folding such as a sum or maximum; use collect with isolated partial containers for mutable accumulation.

The accumulator and combiner must be associative, stateless, and non-interfering, and the identity must be neutral; broken laws yield differing parallel results.

The three-argument overload requires combiner compatibility with the accumulator; the Optional-returning overload throws NullPointerException if the reduced result is null.

The reduction starts with identity 0 and adds 1, 2, and 3 through Integer::sum; the sole stdout line, 6, confirms the accumulated result.

Examples

public class Main {
    public static void main(String[] args) throws Exception {
        int sum = java.util.stream.Stream.of(1, 2, 3).reduce(0, Integer::sum);
        System.out.println(sum);
    }
}

Result

6

The reduction starts with identity 0 and adds 1, 2, and 3 through Integer::sum; the sole stdout line, 6, confirms the accumulated result.

Sources