java.util.Optional 到 java.lang.Iterable?

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

有没有比编写自定义函数更好的替代方法?最好有现货JDK?

如果不是,是否有比以下更好的实现方式:

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

使用 Optional.isPresent() 通常是代码味道 - 它与 != null 没有什么不同。

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

此外,单例 Set 是一个更好的模型......好吧 singleton