Home > Enterprise >  Check whether the given String matches the name of an Enum-element and return that element
Check whether the given String matches the name of an Enum-element and return that element

Time:04-20

Is it possible to check if the given string matches one of enum-names and then return that enum-element?

I tried this:

boolean isValid = Stream.of(Seniority.values())
                .map(Seniority::name)
                .collect(Collectors.toList())
                .contains(experienceLevel.toUpperCase());

if (isValid) {
      return Seniority.valueOf(experienceLevel.toUpperCase());
} else {
      return null;
}

Is it possible to do all these actions by using stream only?

CodePudding user response:

You can also use only valueOf()

If the value doesn't exist you can catch it with IllegalArgumentException.

boolean isValid = true;
try {
    Seniority.valueOf(experienceLevel.toUpperCase());
} catch (IllegalArgumentException e) {
    isValid = false;
}

CodePudding user response:

Is it possible to check if the given string matches one of enum-names and then return that enum-element?

You can use the generic method listed below for any type of enum.

Method EnumSet.allOf() expects a Class<T> object (and T has to be an enum) and returns a set of enum-constants.

Use filter() operation to find the matching enum-element. In place toUpperCase() you can use equalsIgnoreCase() which more expressive in this situation.

Method findFirst() returns an optional object if the stream is empty (i.e. match was not found). If you are not comfortable with it, you can apply orEsle(null) to return a string from the method. But I encourage you to get familiar with the capacities of the Optional instead of treating null as a legal value everywhere.

for more information on the Optional type take a look at this tutorial

public static <T extends Enum<T>> Optional<T> findMatchingEnumName(Class<T> enumClass,
                                                                   String target) {
    return EnumSet.allOf(enumClass).stream()
        .filter(element -> element.name().equalsIgnoreCase(target))
        .findFirst();
}

main() - demo, built-in enum DayOfWeek is used as an example.

public static void main(String[] args) {
    System.out.println(findMatchingEnumName(DayOfWeek.class, "saturday"));
}

Output

Optional[SATURDAY]
  • Related