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();
}
}
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With