In this recipe, you will learn how to use the java.util.Optional class for representing optional values instead of using null references. It was introduced in Java 8 and further enhanced in Java 9—where three more methods were added—or(), ifPresentOrElse(), and stream(). We will demonstrate all of them.
A better way to work with nulls using Optional
Getting ready
The Optional class is a wrapper around a value, which can be null or a value of any type. It was intended to help to avoid the dreaded NullPointerException. But, so far, the introduction of Optional helped to accomplish it only to a degree and mostly in the area of streams and functional programming.
The vision that motivated the creation of the Optional...