是否有一个JDK或guava方法将null转换为空列表 [英] Is there a JDK or guava method to turn a null into an empty list
本文介绍了是否有一个JDK或guava方法将null转换为空列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在JDK或Google guava中有这样的方法
Is there a method like this one in the JDK or Google guava
public static <T> Collection<T> safe(Collection<T> collection)
{
if (collection == null)
{
return new ArrayList<>(0);
} else
{
return collection;
}
}
例如
for (String string : CollectionUtils.safe(foo.canReturnANullListOfStrings()))
{
// do something
}
不会崩溃。
我环顾四周,但找不到任何这样的方法,我想知道如果我错过了,或者有一个原因,为什么这种方便的方法不方便,因此不包括?
I looked around but could not find any such method, and I am wondering if I missed it or if there is a reason why such a handy method is not handy and therefore not included?
推荐答案
Objects.firstNonNull(list, ImmutableList.<Foo>of());
不需要一个专门的方法,这的确是的解决方案,我们建议你立即使用,只要你从一个淘气的API得到一个潜在的null集合,理想情况下不应该首先这样做。
There's no need for a specialized method, and this is indeed the solution we recommend you use immediately whenever you get a potentially-null collection from a naughty API that ideally shouldn't do that in the first place.
这篇关于是否有一个JDK或guava方法将null转换为空列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文