I have two java.util.Optional instances and I want to get an Optional that either:
I had a few encounters with a problem that might've been solved with JDK 9 Optional::or and couldn't because we use JDK 8. Finally I added a util class with this method:
@SafeVarargs
public static Optional firstPresent(final Supplier>... optionals) {
return Stream.of(optionals)
.map(Supplier::get)
.filter(Optional::isPresent)
.findFirst()
.orElse(Optional.empty());
}
Now you can supply any number of optionals to this method and they'll be lazily evaluated like so:
final Optional username = OptionalUtil.firstPresent(
() -> findNameInUserData(user.getBasicData()),
() -> findNameInUserAddress(user.getAddress()),
() -> findDefaultUsername());
Now, findNameInUserAddress will only be called if findNameInUserData returns empty. findDefaultUsername will only be called if both findNameInUserData and findNameInUserAddress return empty etc.