Java Reference
In-Depth Information
contained in the optional. If this application returns true, the optional returns unchanged;
otherwise, the value is filtered away, leaving the optional empty. You can test your
understanding of how the filter method works by working through Quiz 10.2 .
Quiz 10.2: Filtering an optional
Supposing the Person class of our Person/Car/Insurance model also has a method getAge to
access the age of the person, modify the getCarInsuranceName method in listing 10.5 using the
following signature
public String getCarInsuranceName(Optional<Person> person, int minAge)
so that the insurance company name is returned only if the person has an age greater than or
equal to the minAge argument.
Answer:
You can filter from the Optional the person it eventually contains if the age of the person is
greater than the minAge argument by encoding this condition in a predicate and passing this
predicate to the filter method as follows:
public String getCarInsuranceName(Optional<Person> person, int minAge) {
return person.filter(p -> p.getAge() >= minAge)
.flatMap(Person::getCar)
.flatMap(Car::getInsurance)
.map(Insurance::getName)
.orElse("Unknown");
}
In the next section, we investigate the remaining features of the Optional class and give more
practical examples showing various techniques you could use to reimplement the code you write
to manage missing values.
Table 10.1 summarizes the methods of the Optional class.
Search WWH ::




Custom Search