YourReflection
YourReflection

Reputation: 395

Check if a String equals the name of an Enum constant

I would like to check if a given String equals any Enum constant names in my Enum class. Here is an example:

public enum Relation { 
    APPLE("an apple"), 
    BANANA("a banana"); 

    private String value; 

    private Relation(String s) { 
        this.value = s; 
    } 

    public String getValue() { 
        return this.value; 
    }
}

My String would be:

String test = "a banana";

I want to check is the String equals any of the Enum constant names, i.e. "an apple" or "a banana":

if (test.equals(....)) {
 System.out.println("You ordered a banana.");
 }

So far, the examples I found all apply to checking if a String equals an Enum constant. But I want to check if the String equals any of the constant's names as defined in the parenthesis.

Upvotes: 1

Views: 1305

Answers (2)

PeterK
PeterK

Reputation: 1723

You could use a map/ or set to store the enum values, which you would then be able to check for matching values.

This would only be useful if you wanted to do this repeatedly, and reuse the map or set. You would use the map if you wanted to get the related enum.

    Map<String, Relation> map = new HashMap<>();
    for (Relation relation : Relation.values()) {
        map.put(relation.getValue(), relation);
    }

    if(map.containsKey("a banana")){
        System.out.println("You ordered a banana.");
    }

or as a set:

    Set<String> set = new HashSet<>();
    for (Relation relation : Relation.values()) {
        set.add(relation.getValue());
    }

    if(set.contains("a banana")){
        System.out.println("You ordered a banana.");
    }

Upvotes: 0

Louis Wasserman
Louis Wasserman

Reputation: 198113

for (Relation relation : Relation.values()) {
   if (relation.getValue().equals(string)) {
      return relation;
   }
}
return null;

Upvotes: 2

Related Questions