Chaining Optionals in Java 8

piler picture piler · Feb 14, 2015 · Viewed 42.2k times · Source

Looking for a way to chain optionals so that the first one that is present is returned. If none are present Optional.empty() should be returned.

Assuming I have several methods like this:

Optional<String> find1()

I'm trying to chain them:

Optional<String> result = find1().orElse( this::find2 ).orElse( this::find3 );

but of course that doesn't work because orElse expects a value and orElseGet expects a Supplier.

Answer

Sauli T&#228;hk&#228;p&#228;&#228; picture Sauli Tähkäpää · Feb 14, 2015

Use a Stream:

Stream.of(find1(), find2(), find3())
    .filter(Optional::isPresent)
    .map(Optional::get)
    .findFirst();

If you need to evaluate the find methods lazily, use supplier functions:

Stream.of(this::find1, this::find2, this::find3)
    .map(Supplier::get)
    .filter(Optional::isPresent)
    .map(Optional::get)
    .findFirst();