Pun*_*cky 2 java set guava immutable-collections option-type
我希望避免多种if-else情况。下面的代码有更简洁的写法吗?
private Set<String> getValues(Optional<String> one, Optional<String> two) {
if (one.isPresent() && two.isPresent()) {
return ImmutableSet.of(one.get(), two.get());
} else if (one.isPresent()) {
return ImmutableSet.of(one.get());
} else {
return two.isPresent() ? ImmutableSet.of(two.get()) : ImmutableSet.of();
}
}
Run Code Online (Sandbox Code Playgroud)
Ber*_*eri 10
最简单的解决方案是使用Optional.stream(),jdk9+:
private Set<String> getValuesJdk9(Optional<String> one, Optional<String> two) {
return Stream.concat(one.stream(), two.stream())
.collect(Collectors.toUnmodifiableSet());
}
Run Code Online (Sandbox Code Playgroud)
你可以在这里阅读更多
如果您仍在使用 JDK8:
private Set<String> getValuesJdk8(Optional<String> one, Optional<String> two) {
return Stream.of(one, two)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toUnmodifiableSet());
}
Run Code Online (Sandbox Code Playgroud)
还有一个极端的版本,当你可以传递任意数量的参数时
private Set<String> getAllValues(Optional<String>... options) {
return Arrays.stream(options).flatMap(Optional::stream)
.collect(Collectors.toUnmodifiableSet());
}
Run Code Online (Sandbox Code Playgroud)