Looking for a way to chain optionals so that the first one that is present is returned. If none are present Optional.empty() should be returned.
Assumi
Maybe one of
public Optional extends T> firstOf(Optional extends T> first, @SuppressWarnings("unchecked") Supplier>... supp) {
if (first.isPresent()) return first;
for (Supplier> sup : supp) {
Optional extends T> opt = sup.get();
if (opt.isPresent()) {
return opt;
}
}
return Optional.empty();
}
public Optional extends T> firstOf(Optional extends T> first, Stream>> supp) {
if (first.isPresent()) return first;
Stream> present = supp.map(Supplier::get).filter(Optional::isPresent);
return present.findFirst().orElseGet(Optional::empty);
}
will do.
The first one iterates over an array of suppliers. The first non-empty Optional<> is returned. If we don't find one, we return an empty Optional.
The second one does the same with a Stream of Suppliers which is traversed, each one asked (lazily) for their value, which is then filtered for empty Optionals. The first non-empty one is returned, or if no such exists, an empty one.