Streams: Stream.reduce without an identity returns an Optional

The one-argument reduce has no identity value to fall back on for an empty stream, so it wraps its result in an Optional instead of returning the raw type directly.

Code
List<Integer> nums = List.of(3, 7, 2, 9, 4);
Optional<Integer> max = nums.stream().reduce(Integer::max);
System.out.println("Max via reduce: " + max.get());
Optional<Integer> maxEmpty = List.<Integer>of().stream().reduce(Integer::max);
System.out.println("Reduce on empty stream: " + maxEmpty);
Output
Max via reduce: 9
Reduce on empty stream: Optional.empty
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms