Java Reference
In-Depth Information
method. Both of these are shown in Example 4-23 , along with the use of the isPresent
method (which indicates whether the Optional is holding a value).
Example 4-23. Creating an empty Optional and checking whether it contains a value
Optional emptyOptional = Optional . empty ();
Optional alsoEmpty = Optional . ofNullable ( null
null );
assertFalse ( emptyOptional . isPresent ());
// a is defined above
assertTrue ( a . isPresent ());
One approach to using Optional is to guard any call to get() by checking isPresent() . A
neater approach is to call the orElse method, which provides an alternative value in case the
Optional is empty. If creating an alternative value is computationally expensive, the or-
ElseGet method should be used. This allows you to pass in a Supplier that is called only if
the Optional is genuinely empty. Both of these methods are demonstrated in Example 4-24 .
Example 4-24. Using orElse and orElseGet
assertEquals ( "b" , emptyOptional . orElse ( "b" ));
assertEquals ( "c" , emptyOptional . orElseGet (() -> "c" ));
Not only is Optional used in new Java 8 APIs, but it's also just a regular class that you can
use yourself when writing domain classes. This is definitely something to think about when
trying to avoid nullness-related bugs such as uncaught exceptions.
Key Points
▪ A significant performance advantage can be had by using primitive specialized lambda
expressions and streams such as IntStream .
▪ Default methods are methods with bodies on interfaces prefixed with the keyword de-
fault .
▪ The Optional class lets you avoid using null by modeling situations where a value may
not be present.
Search WWH ::




Custom Search