Java Reference
In-Depth Information
10.3.4. Default actions and unwrapping an optional
We decided to read this value using the orElse method that allows you to also provide a default
value that will be returned in the case of an empty optional. The Optional class provides several
instance methods to read the value contained by an Optional instance.
get() is the simplest but also the least safe of these methods. It returns the wrapped value if present
but throws a NoSuchElementException otherwise. For this reason, using this method is almost
always a bad idea unless you're really sure the optional contains a value. In addition, it's not much of
an improvement over nested null checks.
orElse(T other) is the method used in listing 10.5 , and as we noted there, it allows you to provide a
default value for when the optional doesn't contain a value.
orElseGet(Supplier<? extends T> other) is the lazy counterpart of the orElse method, because
the supplier is invoked only if the optional contains no value. You should use this method either when
the default value is time-consuming to create (to gain a little efficiency) or you want to be sure this is
done only if the optional is empty (in which case it's strictly necessary).
orElseThrow(Supplier<? extends X> exceptionSupplier) is similar to the get method in that it
throws an exception when the optional is empty, but in this case it allows you to choose the type of
exception that you want to throw.
ifPresent(Consumer<? super T> consumer) lets you execute the action given as argument if a
value is present; otherwise no action is taken.
The analogies between the Optional class and the Stream interface aren't limited to the map and
flatMap methods. There's a third method, filter, that behaves in a similar fashion, and we
explore it in section 10.3.6 .
10.3.5. Combining two optionals
Let's now suppose that you have a method that given a Person and a Car queries some external
services and implements some quite complex business logic to find the insurance company
offering the cheapest policy for that combination:
public Insurance findCheapestInsurance(Person person, Car car) {
// queries services provided by the different insurance companies
// compare all those data
return cheapestCompany;
}
 
Search WWH ::




Custom Search