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

reduce Returning Optional: Optional<T> reduce(BinaryOperator<T>)

Using reduce without an identity when the stream might be empty, returning Optional to handle absence safely.

reduce Returning Optional: Optional<T> reduce(BinaryOperator<T>)

You'll learn how to use the two-argument form of reduce that safely handles potentially empty streams by returning an Optional.

When you call reduce with only a BinaryOperator (no identity value), the stream might be empty—and there's no meaningful result to return. Java handles this elegantly by wrapping the result in an Optional<T>, which can represent either a present value or absence.

Why Optional Instead of Identity?

Sometimes there's no logical identity value for your operation. For example, finding the maximum number in a stream: what would the identity be? Zero doesn't work (negative numbers exist). Integer.MIN_VALUE is hacky. The honest answer is: if the stream is empty, there is no maximum. That's exactly what Optional.empty() expresses.

Syntax and Usage

Optional<T> reduce(BinaryOperator<T> accumulator)

The method takes only the accumulator function—no identity. If the stream has elements, it returns Optional.of(result). If empty, it returns Optional.empty().

Example: Finding Maximum

List<Integer> numbers = Arrays.asList(3, 7, 2, 9, 1);
Optional<Integer> max = numbers.stream()
    .reduce((a, b) -> a > b ? a : b);

max.ifPresent(System.out::println);  // Prints: 9

With an empty stream:

List<Integer> empty = Arrays.asList();
Optional<Integer> max = empty.stream()
    .reduce((a, b) -> a > b ? a : b);

System.out.println(max.isPresent());  // false

When to Use This Form

Use Optional<T> reduce(BinaryOperator<T>) when:

  • The stream might be empty
  • There's no natural identity value
  • You want explicit handling of the "no result" case

Key Takeaway: The two-argument reduce returns Optional<T> to safely represent the possibility of an empty stream, forcing you to handle absence explicitly rather than risking null or arbitrary default values.