clay clay - 2 months ago 11
Java Question

java.util.Optional to java.lang.Iterable?

Is there a better alternative to writing a custom function? Preferably in the stock JDK?

If not, is there a better implementation than the following:

public static <T> Iterable<T> toIterable(Optional<T> o) {
if (o.isPresent()) {
return Collections.singletonList(o.get());
} else {
return Collections.emptyList();
}
}

Answer

Using Optional.isPresent() is usually code smell - it is no different from != null.

public static <T> Iterable<T> toIterable(Optional<T> o) {
    return o.map(Collections::singleton)
            .orElseGet(Collections::emptySet);
}

Also, a singleton Set is a better model for a ... well singleton.