简体   繁体   中英

How to check if a given string is a part of any given Enum in Java?

I have two different enums and i want to be able to output whether a given string is a part of a enum collection. this is my code:

public class Check {
    public enum Filter{SIZE, DATE, NAME};
    public enum Action{COPY, DELETE, REMOVE};

    public boolean isInEnum(String value, Enum e){
        // check if string value is a part of a given enum
        return false;
    }

    public void main(){
        String filter = "SIZE";
        String action = "DELETE";
                // check the strings
        isInEnum(filter, Filter);
        isInEnum(action, Action);
    }
}

eclipse says that in the last two lines "Filter can't be resolved to a variable" but apart from that it seems that the Enum param in the function "isInEnum" is wrong.

Something is very wrong here can anyone help?

The simplest (and usually most efficient) way is as follows:

public <E extends Enum<E>> boolean isInEnum(String value, Class<E> enumClass) {
  for (E e : enumClass.getEnumConstants()) {
    if(e.name().equals(value)) { return true; }
  }
  return false;
}

and then you call isInEnum(filter, Filter.class) .

If you don't mind using Apache commons lang3 library you can use the following code:

EnumUtils.isValidEnum(Filter.class, filter)

According to the docs :

This method differs from Enum.valueOf(java.lang.Class, java.lang.String) in that it does not throw an exception for an invalid enum name.

Here is a Java 8/streams version of Louis Wasserman's answer. (You can also put this method directly into the Enum class, and remove one of the parameters)

public boolean isInEnum(String value, Class<E> enumClass) {
    return Arrays.stream(enumClass.getEnumConstants()).anyMatch(e -> e.name().equals(value));
  }

I don't have enough points to comment on Simon Tower's answer directly, but here is the method for the second way he mentioned that goes directly in the enum class itself:

 public static boolean isInEnum(String value) {
     return Arrays.stream(EnumClassNameGoesHere.values()).anyMatch(e -> e.name().equals(value));
}

Avoid using a loop to do the validation.

I would suggest using valueOf . This method is built-in to enums, and might be considered for compile time optimization.

This would be like similar to implementing a static Map<String,EnumType> to optimize the lookup, an other consideration you can take.

Drawback is that you would have to use the exception handling mechanism to catch a non-enum value.

Example

public enum DataType {
  //...
  static public boolean has(String value) {
    if (value== null) return false;
    try { 
        // In this implementation - I want to ignore the case
        // if you want otherwise ... remove .toUpperCase()
        return valueOf(value.toUpperCase()); 
    } catch (IllegalArgumentException x) { 
        // the uggly part ...
        return false;
    }
  }
}

Also note that with above type implementation, your code looks much cleaner when calling. Your main would now look something like:

public void main(){
    String filter = "SIZE";
    String action = "DELETE";

    // ...

    if (Filter.has(filter) && Action.has(action)) {
      // Appropriate action
    }
}

Then the other mentioned option is to use a static Map. You can employ such an approach to cache all sort of indexing based on other properties too. In below example, I allow each enum value to have a list of alias names. The lookup index in this case will be case insensitive, by forcing to uppercase.

public enum Command {
  DELETE("del","rm","remove"),
  COPY("cp"),
  DIR("ls");

  private static final Map<String,Command> ALIAS_MAP = new HashMap<String,Command>();
  static {
    for (Command type:Command.values()) {
      ALIAS_MAP.put(type.getKey().toUpper(),type);
      for (String alias:type.aliases) ALIAS_MAP.put(alias.toUpper(),type);
    }
  }

  static public boolean has(String value) {
    return ALIAS_MAP.containsKey(value.toUpper());
  }

  static public Command fromString(String value) {
    if (value == null) throw new NullPointerException("alias null");
    Command command = ALIAS_MAP.get(value);
    if (command == null) throw new IllegalArgumentException("Not an alias: "+value);
    return command;
  }

  private List<String> aliases;
  private Command(String... aliases) {
    this.aliases = Arrays.asList(aliases);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM