Chapter 6. The Optional Type

Sigh, why does everything related to Optional have to take 300 messages?

Brian Goetz, lambda-libs-spec-experts mailing list (October 23, 2013)

The Java 8 API introduced a new class called java.util.Optional<T>. While many developers assume that the goal of Optional is to remove NullPointerExceptions from your code, that’s not its real purpose. Instead, Optional is designed to communicate to the user when a returned value may legitimately be null. This situation can arise whenever a stream of values is filtered by some condition that happens to leave no elements remaining.

In the Stream API, the following methods return an Optional if no elements remain in the stream: reduce, min, max, findFirst, findAny.

An instance of Optional can be in one of two states: a reference to an instance of type T, or empty. The former case is called present, and the latter is known as empty (as opposed to null).

Warning

While Optional is a reference type, it should never be assigned a value of null. Doing so is a serious error.

This chapter looks at the idiomatic ways to use Optional. While the proper use of Optional is likely to be a lively source of discussions in your company,1 the good news is that there are standard recommendations for its proper use. Following these principles should help keep your intentions clear and maintainable.

6.1 Creating an Optional

Problem

You need to return an Optional from an existing value.

Solution

Use Optional.of, Optional.ofNullable ...

Get Modern Java Recipes now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.