Course contentsShow
← Java
Lesson 1506 of 2,87033. Streams API: Terminal OperationsFree lesson

reduce with Identity: T reduce(T identity, BinaryOperator<T>)

Using reduce with an identity value that serves as the starting point and return value for empty streams.

What You'll Learn

You'll learn how to use the reduce operation with an identity value to safely fold a stream into a single result, even when the stream is empty.

Understanding the Identity-Based reduce

The reduce(T identity, BinaryOperator<T> accumulator) form is the safest version of reduce. It takes two arguments:

  1. Identity value: The starting point for the reduction and the default result if the stream is empty
  2. Accumulator function: A binary operator that combines two values into one

Think of it like a running total: You start with an initial amount (identity), then process each element one by one, combining it with your running result.

How It Works

// Summing integers with identity 0
int sum = Stream.of(1, 2, 3, 4)
    .reduce(0, (a, b) -> a + b);
// Result: 10

// Empty stream returns the identity
int emptySum = Stream.<Integer>empty()
    .reduce(0, (a, b) -> a + b);
// Result: 0 (the identity value)

The identity must be the neutral element for your operation:

  • For addition: identity = 0 (because 0 + x = x)
  • For multiplication: identity = 1 (because 1 * x = x)
  • For string concatenation: identity = "" (empty string)

Why the Identity Matters

// Product of numbers
int product = Stream.of(2, 3, 4)
    .reduce(1, (a, b) -> a * b);
// Result: 24

// Finding maximum with a sensible default
int max = Stream.of(5, 2, 8, 1)
    .reduce(Integer.MIN_VALUE, (a, b) -> a > b ? a : b);
// Result: 8

Notice this version returns T directly, not Optional<T>, because the identity guarantees you always have a result.

Key Takeaway: The identity-based reduce provides a safe default value for empty streams and always returns a concrete result rather than an Optional, making it ideal when you have a meaningful starting point for your reduction.