Java: Check if enum contains a given string?

Use the Apache commons lang3 lib instead

 EnumUtils.isValidEnum(MyEnum.class, myValue)

This should do it:

public static boolean contains(String test) {

    for (Choice c : Choice.values()) {
        if (c.name().equals(test)) {
            return true;
        }
    }

    return false;
}

This way means you do not have to worry about adding additional enum values later, they are all checked.

Edit: If the enum is very large you could stick the values in a HashSet:

public static HashSet<String> getEnums() {

  HashSet<String> values = new HashSet<String>();

  for (Choice c : Choice.values()) {
      values.add(c.name());
  }

  return values;
}

Then you can just do: values.contains("your string") which returns true or false.

Tags:

Java

String

Enums