Java Reference
In-Depth Information
Here you invoke a flatMap on the first optional, so if this is empty, the lambda expression
passed to it won't be executed at all and this invocation will just return an empty optional.
Conversely, if the person is present, it uses it as the input of a Function returning an
Optional<Insurance> as required by the flatMap method. The body of this function invokes a
map on the second optional, so if it doesn't contain any car, the Function will return an empty
optional and so will the whole nullSafeFindCheapestInsurance method. Finally, if both the
person and the car are present, the lambda expression passed as argument to the map method
can safely invoke the original findCheapestInsurance method with them.
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 on both classes,
and we explore it next.
10.3.6. Rejecting certain values with filter
Often you need to call a method on an object and check some property. For example, you might
need to check whether the insurance's name is equal to “Cambridge-Insurance.” To do this in a
safe way, you first need to check whether the reference pointing to an Insurance object is null
and then call the getName method, as follows:
Insurance insurance = ...;
if(insurance != null && "CambridgeInsurance".equals(insurance.getName())){
System.out.println("ok");
}
This pattern can be rewritten using the filter method on an Optional object, as follows:
Optional<Insurance> optInsurance = ...;
optInsurance.filter(insurance ->
"CambridgeInsurance".equals(insurance.getName()))
.ifPresent(x -> System.out.println("ok"));
The filter method takes a predicate as an argument. If a value is present in the Optional object
and it matches the predicate, the filter method returns that value; otherwise, it returns an empty
Optional object. If you remember that you can think of an optional as a stream containing at
most a single element, the behavior of this method should be pretty clear. If the optional is
already empty, it doesn't have any effect; otherwise, it applies the predicate to the value
Search WWH ::




Custom Search