我有一个包含可选的Map的类:

 private Optional<ImmutableMap<String, String>> stuff;


在我的类构造函数中,我传递了Map<String, String> inputStuff,其中inputStuff可能是:


null
空的Map
填充的Map


对于前两个实例,我需要存储Optional.absent(),对于第三个实例,我需要存储映射的Optional不可变副本。就处理此问题而言,我能想到的最好的方法是:

    final ImmutableMap<String, String> tmp = ImmutableMap.copyOf(Objects.firstNonNull(inputStuff, ImmutableMap.<String, String>of()));
    if (inputStuff.isEmpty())
    {
      this.stuff = Optional.absent();
    }
    else
    {
      this.stuff = Optional.of(inputStuff);
    }


有没有更清洁的方法来解决这个问题?

最佳答案

为什么不简单地做:

if (inputStuff == null || inputStuff.isEmpty()) {
  this.stuff = Optional.absent();
} else {
  this.stuff = Optional.of(ImmutableMap.copyOf(inputStuff));
}


我看不到为什么要在这里创建一个临时变量的原因。如果您更喜欢使用三元运算符,甚至可以避免重复分配给this.stuff

07-26 04:21