我有一个包含可选项的类Map:
private Optional<ImmutableMap<String, String>> stuff;
Run Code Online (Sandbox Code Playgroud)
在我的类构造函数中,我被传递Map<String, String> inputStuff,其中inputStuff可能是:
nullMapMap对于我需要存储的前两个实例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);
}
Run Code Online (Sandbox Code Playgroud)
有没有更清洁的方法来处理这个?
为什么不简单地做:
if (inputStuff == null || inputStuff.isEmpty()) {
this.stuff = Optional.absent();
} else {
this.stuff = Optional.of(ImmutableMap.copyOf(inputStuff));
}
Run Code Online (Sandbox Code Playgroud)
我没有看到你为什么要在这里创建临时变量的原因.如果您更喜欢使用三元运算符,您甚至可以避免重复的赋值this.stuff.
| 归档时间: |
|
| 查看次数: |
179 次 |
| 最近记录: |