是否有JDK或Guava方法将null转换为空列表?

ams*_*ams 20 java collections guava

在JDK或Google Guava中是否有像这样的方法

public static <T> Collection<T> safe(Collection<T> collection) {
    if (collection == null) {
        return new ArrayList<>(0);
    } else {
        return collection;
    }
}
Run Code Online (Sandbox Code Playgroud)

例如,如果某些东西返回空列表,则很容易在增强的循环上崩溃

for (String string : CollectionUtils.safe(foo.canReturnANullListOfStrings())) {
    // do something
}
Run Code Online (Sandbox Code Playgroud)

不会崩溃.

我环顾四周但找不到任何这样的方法,我想知道我是否错过了它,或者是否有理由为什么这样一个方便的方法不方便因此不包括在内?

Lou*_*man 25

Objects.firstNonNull(list, ImmutableList.<Foo>of());
Run Code Online (Sandbox Code Playgroud)

没有必要使用专门的方法,这确实是我们建议您每当从顽皮的API获得可能为空的集合时立即使用的解决方案,理想情况下不应该首先执行此操作.

  • 这是多么好的方法啊,让简单的任务看起来很复杂。使用下面评论中的 apache 集合 ListUtils.emptyIfNull 。读起来好多了。 (3认同)

Jef*_*rey 16

Apache Collections 4有一个通用的方法 ListUtils.emptyIfNull(List<T> list)

这是doc:https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/ListUtils.html


Voj*_*jta 12

在Java 8中,可以使用:

Optional.ofNullable(foo.canReturnANullListOfStrings()).orElse(Collections.emptyList());
Run Code Online (Sandbox Code Playgroud)


Mat*_*fek 6

Java 9 更新: java.util.Objects.requireNonNullElse(collection, List.<T>of())

<T>仍然需要。