Home > Blockchain >  refactor the code without using conditional blocks
refactor the code without using conditional blocks

Time:11-18

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



CodePudding user response:

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

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.toSet());
    }
  •  Tags:  
  • java
  • Related