Search code examples
javasetoption-typeguavaimmutable-collections

Guava - Collect values extracted from two Optionals into an ImmutableSet


I am looking to avoid multiple if-else conditions. Is there a more concise way of writing the below code?

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.toUnmodifiableSet());
        }
    

    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.toUnmodifiableSet());
        }
    

    And one extreme version, when You can pass any number of arguments

       private Set<String> getAllValues(Optional<String>... options) {
            return Arrays.stream(options).flatMap(Optional::stream)
                    .collect(Collectors.toUnmodifiableSet());
        }