Java Reference
In-Depth Information
Figure 10.2. Comparing the map methods of Streams and Optionals
This looks useful, but how could you use this to write the previous code, which was chaining
several method calls in a safe way?
public String getCarInsuranceName(Person person) {
return person.getCar().getInsurance().getName();
}
We have to look at another method supported by Optional called flatMap!
10.3.3. Chaining Optional objects with flatMap
Because you've just learned how to use map, your first reaction may be that you can rewrite the
previous code using map as follows:
Optional<Person> optPerson = Optional.of(person);
Optional<String> name =
optPerson.map(Person::getCar)
.map(Car::getInsurance)
.map(Insurance::getName);
Unfortunately, this code doesn't compile. Why? The variable optPeople is of type
Optional<People>, so it's perfectly fine to call the map method. But getCar returns an object of
type Optional<Car> (as presented in listing 10.4 ) . This means the result of the map operation is
an object of type Optional<Optional<Car>>. As a result, the call to getInsurance is invalid
because the outermost optional contains as its value another optional, which of course doesn't
support the getInsurance method. Figure 10.3 illustrates the nested optional structure you'd get.
 
Search WWH ::




Custom Search