清洁番石榴方式来处理可能为空的集合

我有一个方法,它接受一个参数Collection foos ,它可能是NULL。 我希望最终将输入的本地副本作为ImmutableSet 。 现在我的代码看起来像这样:

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

有更清洁的方法吗? 如果foos是一个简单的参数,我可以做类似Objects.firstNonNull(foos, Optional.of())东西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())); 

Collection是一个像任何其他参考,所以你可以这样做:

 ImmutableSet.copyOf(Optional.fromNullable(foos).or(ImmutableSet.of())); 

但是这一点变得非常少。 更简单:

 foos == null ? ImmutableSet.of() : ImmutableSet.copyOf(foos);