Java 9 and above:
firstOptional.or(() -> secondOptional);
Java 8 and below
If you want to avoid mentioning firstOptional
twice, you’d probably have to go with something like
firstOptional.map(Optional::of).orElse(secondOptional);
or
Optional.ofNullable(firstOptional.orElse(secondOptional.orElse(null)));
But the most readable variant is probably to simply do
Optional<...> opt = firstOptional.isPresent() ? firstOptional
: secondOptional.isPresent() ? secondOptional
: Optional.empty();
If someone stumbles across this question but has a list of optionals, I’d suggest something like
Optional<...> opt = optionals.stream()
.filter(Optional::isPresent)
.findFirst()
.orElse(Optional.empty());