Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cascade methods, each returning an Java8 Optional<> [duplicate]

I have several methods, that each are returning an optional string. How do I combine then, so that java calls each method, until it finds a result?

I'd like to end up with something like this, but there is not orElseFlatMap() method:

import java.util.Optional;

public class OptionalCascade {

    public static void main(String[] args) {
        Optional<String> result = 

                // try to get a result with method A
                methodA()

                // if method A did not return anything, then try method B
                .orElseFlatMap(methodB());
    }


    static Optional<String> methodA() {
        return Optional.empty();
    }

    static Optional<String> methodB() {
        return Optional.empty();
    }
}
like image 235
slartidan Avatar asked Sep 18 '15 10:09

slartidan


1 Answers

Assuming you want to use standard methods and have single-expression solution, I can come up only with this:

Optional<String> result = Optional.ofNullable(methodA().orElseGet(
        () -> methodB().orElse(null)));

Ugly. Alternatively you may write your own static method:

public static <T> Optional<T> orElseFlatMap(Optional<T> optional,
        Supplier<Optional<T>> other) {
    return optional.isPresent() ? optional : other.get();
}

Optional<String> result = orElseFlatMap(methodA(), () -> methodB());
like image 77
Tagir Valeev Avatar answered Oct 24 '22 16:10

Tagir Valeev