In my previous post, I wrote about how you can use optionals to model the absence of a value. Optionals also contain a useful filter
method, which takes a predicate as an argument. If a value is present in the Optional
object and the predicate is satisfied, the filter
method returns that value; otherwise it returns an empty Optional
object.
For example, let's suppose that the Phone
class of the Person/Phone/Camera/Resolution
model has a method to get the operating system of the phone, and we want to get the camera resolution of "Android" phones only. We can modify the getPhoneCameraResolution
method to use a filter, as shown below:
public Resolution getPhoneCameraResolution(final Optional<Person> person) { return person.flatMap(Person::getPhone) // returns Optional<Phone> .filter(phone -> phone.getOS() == OS.Android) // match Android phones only .flatMap(Phone::getCamera) // returns Optional<Camera> .map(Camera::getResolution) // returns Optional<Resolution> .orElse(Resolution.UNKNOWN); // returns Resolution or UNKNOWN if not found }
Related posts:
Java 8: Using Optional Objects
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.