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获得可能为空的集合时立即使用的解决方案,理想情况下不应该首先执行此操作.
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)