5. Optional
Java 8 comes with the Optional class in the java.util package for avoiding null return values (and thus NullPointerException).
It is very similar to Google Guava’s Optional,
which is similar to Nat Pryce’s Maybe class
and Scala’s Option class.
You can use Optional.of(x) to wrap a non-null value, Optional.empty() to represent a missing value,
or Optional.ofNullable(x) to create an Optional from a reference that may or may not be null.
After creating an instance of Optional, you then use isPresent() to determine if the there is a value and get() to get the value.
Optional provides a few other helpful methods for dealing with missing values:
-
orElse(T)– Returns the given default value if the Optional is empty. -
orElseGet(Supplier<T>)– Calls on the given Supplier to provide a value if the Optional is empty. -
orElseThrow(Supplier<X extends Throwable>)– Calls on the given Supplier for an exception to throw if the Optional is empty.
It also includes functional style (lambda friendly) methods, like the following:
-
filter(Predicate<? super T> predicate)– Filters the value and returns a new Optional. -
flatMap(Function<? super T,Optional<U>> mapper)– Performs a mapping operation which returns an Optional. -
ifPresent(Consumer<? super T> consumer)– Executes the given Consumer only if there is a value present (no return value). -
map(Function<? super T,? extends U> mapper)– Uses the given mapping Function and returns a new Optional.