清洁番石榴方式来处理可能为空的集合 [英] Clean Guava way to handle possibly-null collection

查看:128
本文介绍了清洁番石榴方式来处理可能为空的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法,它接受一个参数 Collection< Foo> foos ,可能为NULL。我想以 ImmutableSet 结尾输入本地副本。现在我的代码如下所示:

I have a method which takes an argument Collection<Foo> foos, which could be NULL. I want to end up with a local copy of the input as an ImmutableSet. Right now my code looks like this:

if (foos == null)
{
  this.foos = ImmutableSet.of();
}
else
{
  this.foos = ImmutableSet.copyOf(foos);
}

有更简洁的方法吗?如果 foos 是一个简单的参数,我可以做一些像 Objects.firstNonNull(foos,Optional.of())但是我不确定是否有类似处理集合的东西。

Is there a cleaner way to do this? If foos was a simple parameter I could do something like Objects.firstNonNull(foos, Optional.of()) but I'm not sure if there is something similar to handle collections.

推荐答案

我不明白为什么你不能使用 Objects.firstNonNull

I don't see why you couldn't use Objects.firstNonNull:

this.foos = ImmutableSet.copyOf(Objects.firstNonNull(foos, ImmutableSet.of()));

你可以用静态导入保存一些输入,如果这是你的事情:

You can save some typing with static imports, if that's your thing:

import static com.google.common.collect.ImmutableSet.copyOf;
import static com.google.common.collect.ImmutableSet.of;
// snip...
this.foos = copyOf(Objects.firstNonNull(foos, of()));

这篇关于清洁番石榴方式来处理可能为空的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆