Using the Optional class
In this section, we will examine the use of the Optional
class to make our programs more robust and maintainable. The Optional
class is useful for returning values from a method and supporting fluent programming.
We will examine these scenarios and illustrate the creation and use of various Optional
methods. These examples will illustrate how to handle situations where an empty Optional
instance is encountered.
The Optional
class is not intended to avoid all null pointer situations. Rather, it provides a means of defining better API interfaces where the user can clearly see when an empty value is possible.
There are also three classes that support specialized numeric versions of the Optional
class: OptionalInt
, OptionalLong
, and OptionalDouble
. They possess many of the same methods, but are designed to work with integer, double, and long data types, respectively. However, they do not possess the map
, flatMap
, and filter
methods found in the Optional
class. In addition...