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