Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

refactor the code without using conditional blocks

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading