Skip to content
Advertisement

How to peek on an Optional?

I want to use the fluent api of Optional and apply two Consumers to it.

I’m dreaming about something like this:

Optional.ofNullable(key)
    .map(Person::get)
    .ifPresent(this::printName)
    .ifPresent(this::printAddress); // not compiling, because ifPresent is void

How do I apply several Consumers to an Optional?

Answer

You can use this syntax:

ofNullable(key)
    .map(Person::get)
    .map(x -> {printName(x);return x;})
    .map(x -> {printAddress(x);return x;});
Advertisement