Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

enums

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?

like image 292
Tom Avatar asked Apr 17 '12 21:04

Tom


People also ask

Can we compare string with enum in Java?

Comparing String to Enum type in JavaFor comparing String to Enum type you should convert enum to string and then compare them. For that you can use toString() method or name() method. toString()- Returns the name of this enum constant, as contained in the declaration.

How do you check if a value is present in an enum or not?

Enum. IsDefined is a check used to determine whether the values exist in the enumeration before they are used in your code. This method returns a bool value, where a true indicates that the enumeration value is defined in this enumeration and false indicates that it is not. The Enum .

How can I lookup a Java enum from its string value?

To lookup a Java enum from its string value, we can use the built-in valueOf method of the Enum. However, if the provided value is null, the method will throw a NullPointerException exception. And if the provided value is not existed, an IllegalArgumentException exception.


1 Answers

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).

like image 178
Louis Wasserman Avatar answered Sep 22 '22 14:09

Louis Wasserman