【问题标题】:Clean Guava way to handle possibly-null collection清洁 Guava 方法来处理可能为空的集合
【发布时间】:2013-07-03 17:11:35
【问题描述】:

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

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

有没有更清洁的方法来做到这一点?如果foos 是一个简单的参数,我可以执行Objects.firstNonNull(foos, Optional.of()) 之类的操作,但我不确定是否有类似处理集合的操作。

【问题讨论】:

    标签: java guava


    【解决方案1】:

    我不明白你为什么不能使用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()));
    

    【讨论】:

    • +1 值得指出的是,copyOf 足够聪明,可以简单地返回输入,如果它是 ImmutableSet
    • @PaulBellora 我相信你刚刚做到了。 :)
    • 不幸的是,ImmutableSet.<Foo>of() 也可能是必要的。
    【解决方案2】:

    Collection 与其他任何引用一样,因此您可以这样做:

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

    但是,这已经变得很难写了。更简单:

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

    【讨论】:

    • 第二个示例的优点是在不需要时不创建空集合。即使传递的集合不为空,MattBall 的答案也会始终创建空的 Set
    • @JohnB ImmutableSet.of() returns a singleton.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-21
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多