I am looking to avoid multiple if-else conditions. Is there a concise way of refactoring the below?
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();
}
}
>Solution :
The simplest solution would be to use Optional.stream(), jdk9+:
private Set<String> getValuesJdk9(Optional<String> one, Optional<String> two) {
return Stream.concat(one.stream(), two.stream())
.collect(Collectors.toSet());
}
You can read more here
If You are using JDK8 still:
private Set<String> getValuesJdk8(Optional<String> one, Optional<String> two) {
return Stream.of(one, two)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toSet());
}