Scrivio Interview library
ConceptIntermediate5 min read · updated 12 November 2026

Which stream terminal operations return Optional and why? Why does max on an empty stream return Optional rather than null?

The Stream terminal operations findFirst, findAny, min, max and reduce without an identity return Optional, because on an empty stream they have no result, and null would be ambiguous and easy to ignore. Because Optional cannot hold null, findFirst throws NullPointerException if the element it finds is null. Primitive streams return OptionalInt, OptionalLong or OptionalDouble instead, and average on an empty IntStream returns an empty OptionalDouble.

Why this question is asked

We use stream terminal operations so often that their return types feel natural, but the choice behind them is deliberate. Some operations always have an answer, like count, while others only have one when the stream has elements, and the API marks that difference with Optional. Interviewers ask this to see whether we understand that design and its edge cases, especially the surprising NullPointerException from findFirst. In this answer, we will recap terminal operations, list the ones that return Optional, explain why null would be the wrong answer, look at the null element case, and finish with primitive streams.

1A Quick Recap of Terminal Operations

A stream pipeline has a source, zero or more intermediate operations such as filter and map, and one terminal operation that produces the result and ends the stream. Some terminal operations produce a value for every possible stream: count returns 0 for an empty stream, collect returns an empty list, and reduce with an identity returns the identity. Others can only produce a value if at least one element exists, and those are the ones that return Optional.

Terminal operations and what an empty stream gives
OperationReturn typeOn an empty stream
findFirst(), findAny()Optional<T>Optional.empty
min(cmp), max(cmp)Optional<T>Optional.empty
reduce(BinaryOperator)Optional<T>Optional.empty
reduce(identity, op)Tthe identity
count()long0
IntStream.max(), min()OptionalIntOptionalInt.empty
IntStream.average()OptionalDoubleOptionalDouble.empty
IntStream.sum()int0

2The Operations That Return Optional

Here is each operation on a small stream and on an empty one.

Java
List<Integer> prices = List.of(40, 15, 70);
List<Integer> none = List.of();
prices.stream().findFirst(); // Optional[40]
prices.stream().max(Comparator.naturalOrder()); // Optional[70]
prices.stream().reduce(Integer::sum); // Optional[125]
none.stream().max(Comparator.naturalOrder()); // Optional.empty
none.stream().reduce(Integer::sum); // Optional.empty
none.stream().reduce(0, Integer::sum); // 0: the identity is the answer for no elements

Notice the difference between the two forms of reduce. With an identity, such as 0 for addition, an empty stream has a well-defined answer, so the result is a plain value. Without one, there is nothing to return for an empty stream, so the result is Optional. The same reasoning applies to max: there is no maximum of nothing, and the API refuses to invent one.

3Why Not Return null?

Returning null for "no result" has two problems. First, it is easy to ignore: the caller of max would get a NullPointerException later, far from the cause. Optional puts the empty case into the type, so the caller must decide what to do before using the value.

Second, null would be ambiguous. In general, a stream may contain null elements, so a method that returned null could mean either "the stream was empty" or "the element found was null". Optional removes that ambiguity by design: an empty Optional always means there was no result, because Optional cannot hold null at all.

Java
Integer highest = prices.stream().max(Comparator.naturalOrder()).orElse(0); // 70
String label = none.stream().map(p -> "price " + p).findFirst().orElse("none"); // "none"

4When findFirst Meets a null Element

The flip side of "Optional cannot hold null" is that these operations fail if the result they select is null. They cannot wrap it, and returning an empty Optional would wrongly say the stream was empty.

Java
Stream.of("a", null).findFirst(); // Optional[a]: the null is never reached
Stream.of(null, "a").findFirst(); // NullPointerException: the first element is null
Stream.of("b", null, "a")
.max(Comparator.nullsFirst(Comparator.naturalOrder())); // Optional[b]
Stream.of("b", null)
.min(Comparator.nullsFirst(Comparator.naturalOrder())); // NullPointerException: min is null
Step throughHow findFirst decides its result
  1. Does the stream have an element?
    YesTake the first elementNoReturn Optional.empty
  2. Is that element null?
    YesThrow NullPointerExceptionNoReturn Optional.of(element)

2 steps in order. Play them, or step through them one at a time.

So the exception depends on which element is selected, not on whether nulls exist somewhere in the stream. The usual fix is to remove nulls before the terminal operation with filter(Objects::nonNull), or, better, to stop nulls from entering the collection in the first place.

5Primitive Streams and Their Optionals

IntStream, LongStream and DoubleStream avoid boxing every number into an Integer, Long or Double. For the same reason, their terminal operations return OptionalInt, OptionalLong and OptionalDouble rather than Optional<Integer>. These classes hold a primitive and offer getAsInt, orElse, orElseGet, orElseThrow and ifPresent, but they have no map, filter or flatMap.

Java
IntStream.of(4, 9, 2).max(); // OptionalInt[9]
IntStream.empty().max(); // OptionalInt.empty
IntStream.of(4, 9, 2).average(); // OptionalDouble[5.0]
IntStream.empty().average(); // OptionalDouble.empty
IntStream.empty().sum(); // 0
IntStream.empty().average().orElse(0.0); // 0.0

Notice that sum returns a plain int, because the sum of no numbers is naturally 0, while average returns OptionalDouble, because the average of no numbers would be a division by zero. The API is consistent: whenever an empty input has a mathematically sensible answer, we get a value, and whenever it does not, we get an empty optional.

6Follow-up questions

What is the difference between findFirst and findAny?

findFirst returns the first element in encounter order, while findAny may return any element. On a sequential stream they usually behave the same, but on a parallel stream findAny can return whichever element a thread finds first, which is faster because it does not need to coordinate order. Use findAny when any match will do.

Do Collectors have the same pattern?

Yes. Collectors.maxBy and minBy produce Optional<T>, and Collectors.reducing without an identity also produces an Optional, for the same reason. Collectors.averagingInt, on the other hand, returns 0.0 for no elements, so it is worth checking each collector's documentation.

How do you get the max of a stream that may contain nulls?

Filter them out with filter(Objects::nonNull) before calling max, or use a comparator such as Comparator.nullsFirst and accept that a null result will throw. Filtering is usually the clearer choice, because a null maximum is rarely meaningful.

7Conclusion

In this answer, we saw that findFirst, findAny, min, max and reduce without an identity return Optional because an empty stream has no result for them, while operations like count, sum and reduce with an identity always have one. Optional is better than null because it forces the caller to handle absence and cannot be confused with a null element. That same rule makes findFirst and its relatives throw NullPointerException when the selected element is null. Primitive streams return OptionalInt, OptionalLong and OptionalDouble, and average on an empty IntStream gives an empty OptionalDouble while sum gives 0.

What to say in the interviewAbout 80 seconds aloud

Open with

The terminal operations that return Optional are findFirst, findAny, min, max, and reduce without an identity. They're exactly the ones that have no sensible answer for an empty stream: there's no first element and no maximum of nothing.

Then, if they want more

By contrast count returns zero, reduce with an identity returns the identity, and collect returns an empty collection, because those do have an answer. The API returns Optional rather than null for two reasons. Null is easy to ignore, so the caller would crash later far from the cause, whereas Optional forces them to decide with orElse or orElseThrow.

And null would be ambiguous, because a stream can contain null elements, so null could mean empty stream or the element was null. Optional can't hold null, so empty always means no result. The consequence is that if the element selected is null, findFirst or max throws NullPointerException; Stream.of(null, "a").findFirst() throws, while Stream.of("a", null).findFirst() is fine.

I'd filter nulls out first. Primitive streams follow the same idea with OptionalInt, OptionalLong and OptionalDouble, which avoid boxing but have no map or filter. IntStream.empty().average() gives an empty OptionalDouble, while sum gives zero, since the average of nothing is undefined but the sum is zero.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Which stream terminal operations return Optional and why? Why does max on an empty...": https://scrivio-interview-library.netlify.app/java/optional/d3b4638cd3/