javalambdajava-8option-type

Chaining Optionals in Java 8


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.


Solution

  • 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();