我有一个需要参数的方法Collection<Foo> foos
,可能为 NULL。我想最终获得输入的本地副本作为ImmutableSet
。现在我的代码如下所示:
if (foos == null)
{
this.foos = ImmutableSet.of();
}
else
{
this.foos = ImmutableSet.copyOf(foos);
}
有没有更干净的方法来做到这一点?如果foos
是一个简单的参数我可以做类似的事情Objects.firstNonNull(foos, Optional.of())
但我不确定是否有类似的东西来处理集合。
我不明白你为什么不能使用Objects.firstNonNull
:
this.foos = ImmutableSet.copyOf(Objects.firstNonNull(foos, ImmutableSet.of()));
如果您喜欢的话,您可以使用静态导入来节省一些输入:
import static com.google.common.collect.ImmutableSet.copyOf;
import static com.google.common.collect.ImmutableSet.of;
// snip...
this.foos = copyOf(Objects.firstNonNull(foos, of()));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)