Java: Check if enum contains a given string?

JavaStringEnums

Java Problem Overview


Here's my problem - I'm looking for (if it even exists) the enum equivalent of ArrayList.contains();.

Here's a sample of my code problem:

enum choices {a1, a2, b1, b2};

if(choices.???(a1)}{
//do this
} 

Now, I realize that an ArrayList of Strings would be the better route here but I have to run my enum contents through a switch/case elsewhere. Hence my problem.

Assuming something like this doesn't exist, how could I go about doing it?

Java Solutions


Solution 1 - Java

Use the Apache commons lang3 lib instead

 EnumUtils.isValidEnum(MyEnum.class, myValue)

Solution 2 - Java

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.

Solution 3 - Java

You can use Enum.valueOf()

enum Choices{A1, A2, B1, B2};

public class MainClass {
  public static void main(String args[]) {
    Choices day;

    try {
       day = Choices.valueOf("A1");
       //yes
    } catch (IllegalArgumentException ex) {  
        //nope
  }
}

If you expect the check to fail often, you might be better off using a simple loop as other have shown - if your enums contain many values, perhaps builda HashSet or similar of your enum values converted to a string and query that HashSet instead.

Solution 4 - Java

If you are using Java 1.8, you can choose Stream + Lambda to implement this:

public enum Period {
    DAILY, WEEKLY
};

//This is recommended
Arrays.stream(Period.values()).anyMatch((t) -> t.name().equals("DAILY1"));
//May throw java.lang.IllegalArgumentException
Arrays.stream(Period.values()).anyMatch(Period.valueOf("DAILY")::equals);

Solution 5 - Java

Guavas Enums could be your friend

Like e.g. this:

enum MyData {
    ONE,
    TWO
}

@Test
public void test() {

    if (!Enums.getIfPresent(MyData.class, "THREE").isPresent()) {
        System.out.println("THREE is not here");
    }
}

Solution 6 - Java

Even better:

enum choices {
   a1, a2, b1, b2;

  public static boolean contains(String s)
  {
      for(choices choice:values())
           if (choice.name().equals(s)) 
              return true;
      return false;
  } 

};

Solution 7 - Java

A couple libraries have been mentioned here, but I miss the one that I was actually looking for: Spring!

There is the ObjectUtils#containsConstant which is case insensitive by default, but can be strict if you want. It is used like this:

if(ObjectUtils.containsConstant(Choices.values(), "SOME_CHOISE", true)){
// do stuff
}

Note: I used the overloaded method here to demonstrate how to use case sensitive check. You can omit the boolean to have case insensitive behaviour.

Be careful with large enums though, as they don't use the Map implementation as some do...

As a bonus, it also provides a case insensitive variant of the valueOf: ObjectUtils#caseInsensitiveValueOf

Solution 8 - Java

You can first convert the enum to List and then use list contains method

enum Choices{A1, A2, B1, B2};

List choices = Arrays.asList(Choices.values());

//compare with enum value 
if(choices.contains(Choices.A1)){
   //do something
}

//compare with String value
if(choices.contains(Choices.valueOf("A1"))){
   //do something
}

Solution 9 - Java

Few assumptions:

  1. No try/catch, as it is exceptional flow control

  2. 'contains' method has to be quick, as it usually runs several times.

  3. Space is not limited (common for ordinary solutions)

    import java.util.HashSet; import java.util.Set;

    enum Choices { a1, a2, b1, b2;

     private static Set<String> _values = new HashSet<>();
    
     // O(n) - runs once
     static{
     	for (Choices choice : Choices.values()) {
     		_values.add(choice.name());
     	}
     }
    
     // O(1) - runs several times
     public static boolean contains(String value){
     	return _values.contains(value);
     }
    

    }

Solution 10 - Java

You can use this

YourEnum {A1, A2, B1, B2}

boolean contains(String str){ 
    return Sets.newHashSet(YourEnum.values()).contains(str);
}                                  

Update suggested by @wightwulf1944 is incorporated to make the solution more efficient.

Solution 11 - Java

Java Streams provides elegant way to do that

Stream.of(MyEnum.values()).anyMatch(v -> v.name().equals(strValue))

Returns: true if any elements of the stream match the provided value, otherwise false

Solution 12 - Java

I don't think there is, but you can do something like this:

enum choices {a1, a2, b1, b2};

public static boolean exists(choices choice) {
   for(choice aChoice : choices.values()) {
      if(aChoice == choice) {
         return true;
      }
   }
   return false;
}

Edit:

Please see Richard's version of this as it is more appropriate as this won't work unless you convert it to use Strings, which Richards does.

Solution 13 - Java

Why not combine Pablo's reply with a valueOf()?

public enum Choices
{
    a1, a2, b1, b2;
    
    public static boolean contains(String s) {
        try {
            Choices.valueOf(s);
            return true;
        } catch (Exception e) {
            return false;
        }
}

Solution 14 - Java

You can make it as a contains method:

enum choices {a1, a2, b1, b2};
public boolean contains(String value){
    try{
		EnumSet.allOf(choices.class).contains(Enum.valueOf(choices.class, value));
		return true;
	}catch (Exception e) {
		return false;
	}
}

or you can just use it with your code block:

try{
	EnumSet.allOf(choices.class).contains(Enum.valueOf(choices.class, "a1"));
    //do something
}catch (Exception e) {
	//do something else
}

Solution 15 - Java

I would just write,

Arrays.stream(Choice.values()).map(Enum::name).collect(Collectors.toList()).contains("a1");

Enum#equals only works with object compare.

Solution 16 - Java

This approach can be used to check any Enum, you can add it to an Utils class:

public static <T extends Enum<T>> boolean enumContains(Class<T> enumerator, String value)
{
	for (T c : enumerator.getEnumConstants()) {
		if (c.name().equals(value)) {
			return true;
		}
	}
	return false;
}

Use it this way:

boolean isContained = Utils.enumContains(choices.class, "value");

Solution 17 - Java

This one works for me:

Arrays.asList(YourEnum.values()).toString().contains("valueToCheck");

Solution 18 - Java

I created the next class for this validation

public class EnumUtils {

    public static boolean isPresent(Enum enumArray[], String name) {
        for (Enum element: enumArray ) {
            if(element.toString().equals(name))
                return true;
        }
        return false;
    }

}

example of usage :

public ArrivalEnum findArrivalEnum(String name) {

    if (!EnumUtils.isPresent(ArrivalEnum.values(), name))
        throw new EnumConstantNotPresentException(ArrivalEnum.class,"Arrival value must be 'FROM_AIRPORT' or 'TO_AIRPORT' ");
    
    return ArrivalEnum.valueOf(name);
}

Solution 19 - Java

If you are Using Java 8 or above, you can do this :

boolean isPresent(String testString){
      return Stream.of(Choices.values()).map(Enum::name).collect(Collectors.toSet()).contains(testString);
}

Solution 20 - Java

You can use valueOf("a1") if you want to look up by String

Solution 21 - Java

It is an enum, those are constant values so if its in a switch statement its just doing something like this:

case: val1
case: val2

Also why would you need to know what is declared as a constant?

Solution 22 - Java

With guava it's even simpler:

boolean isPartOfMyEnum(String myString){

return Lists.newArrayList(MyEnum.values().toString()).contains(myString);

}

Solution 23 - Java

This combines all of the approaches from previous methods and should have equivalent performance. It can be used for any enum, inlines the "Edit" solution from @Richard H, and uses Exceptions for invalid values like @bestsss. The only tradeoff is that the class needs to be specified, but that turns this into a two-liner.

import java.util.EnumSet;

public class HelloWorld {

static enum Choices {a1, a2, b1, b2}

public static <E extends Enum<E>> boolean contains(Class<E> _enumClass, String value) {
    try {
        return EnumSet.allOf(_enumClass).contains(Enum.valueOf(_enumClass, value));    
    } catch (Exception e) {
        return false; 
    }
}

public static void main(String[] args) {
    for (String value : new String[] {"a1", "a3", null}) {
        System.out.println(contains(Choices.class, value));
    }
}

}

Solution 24 - Java

com.google.common.collect.Sets.newHashSet(MyEnum.values()).contains("myValue")

Solution 25 - Java

solution to check whether value is present as well get enum value in return :

protected TradeType getEnumType(String tradeType) {
    if (tradeType != null) {
        if (EnumUtils.isValidEnum(TradeType.class, tradeType)) {
            return TradeType.valueOf(tradeType);
        }
    }
    return null;
}

Solution 26 - Java

  Set.of(CustomType.values())
     .contains(customTypevalue) 

Solution 27 - Java

you can also use : com.google.common.base.Enums

Enums.getIfPresent(varEnum.class, varToLookFor) returns an Optional

Enums.getIfPresent(fooEnum.class, myVariable).isPresent() ? Enums.getIfPresent(fooEnum.class, myVariable).get : fooEnum.OTHERS

Solution 28 - Java

EnumUtils.isValidEnum might be the best option if you like to import Apache commons lang3. if not following is a generic function I would use as an alternative.

private <T extends Enum<T>> boolean enumValueExists(Class<T> enumType, String value) {
    boolean result;
    try {
        Enum.valueOf(enumType, value);
        result = true;
    } catch (IllegalArgumentException e) {
        result = false;
    }
    return result;
}

And use it as following

if (enumValueExists(MyEnum.class, configValue)) {
	// happy code
} else {
	// angry code
}

Solution 29 - Java

While iterating a list or catching an exception is good enough for most cases I was searching for something reusable that works well for large enums. In it end, I end up writing this:

public class EnumValidator {

    private final Set<String> values;

    private EnumValidator(Set<String> values) {
        this.values = values;
    }

    public static <T extends Enum<T>> EnumValidator of(Class<T> enumType){
        return new EnumValidator(Stream.of(enumType.getEnumConstants()).map(Enum::name).collect(Collectors.toSet()));
    }

    public boolean isPresent(String et){
        return values.contains(et);
    }
    
}

Solution 30 - Java

Java 8+ stream + set way:

    // Build the set.
    final Set<String> mySet = Arrays//
      .stream(YourEnumHere.values())//
      .map(Enum::name)//
      .collect(Collectors.toSet());

    // Reuse the set for contains multiple times.
    mySet.contains(textA);
    mySet.contains(textB);
    ...

Solution 31 - Java

public boolean contains(Choices value) {
   return EnumSet.allOf(Choices.class).contains(value);
}

Solution 32 - Java

enum are pretty powerful in Java. You could easily add a contains method to your enum (as you would add a method to a class):

enum choices {
  a1, a2, b1, b2;

  public boolean contains(String s)
  {
      if (s.equals("a1") || s.equals("a2") || s.equals("b1") || s.equals("b2")) 
         return true;
      return false;
  } 

};

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJaredView Question on Stackoverflow
Solution 1 - JavaRaphCView Answer on Stackoverflow
Solution 2 - JavaRichard HView Answer on Stackoverflow
Solution 3 - JavanosView Answer on Stackoverflow
Solution 4 - JavaHao MaView Answer on Stackoverflow
Solution 5 - JavaH6.View Answer on Stackoverflow
Solution 6 - JavaDevashish BansalView Answer on Stackoverflow
Solution 7 - JavaBitfullByteView Answer on Stackoverflow
Solution 8 - JavaBikramView Answer on Stackoverflow
Solution 9 - JavaAndreyView Answer on Stackoverflow
Solution 10 - JavagreperrorView Answer on Stackoverflow
Solution 11 - JavaSourabhView Answer on Stackoverflow
Solution 12 - JavajluzwickView Answer on Stackoverflow
Solution 13 - JavaKarthik VView Answer on Stackoverflow
Solution 14 - JavaaqteifanView Answer on Stackoverflow
Solution 15 - JavaSwadeshiView Answer on Stackoverflow
Solution 16 - JavaAntónio AlmeidaView Answer on Stackoverflow
Solution 17 - JavaEDiazView Answer on Stackoverflow
Solution 18 - JavaIgnacio Jeria GarridoView Answer on Stackoverflow
Solution 19 - JavachiragView Answer on Stackoverflow
Solution 20 - JavaAmir AfghaniView Answer on Stackoverflow
Solution 21 - JavaWoot4MooView Answer on Stackoverflow
Solution 22 - JavachaiyachaiyaView Answer on Stackoverflow
Solution 23 - Javauser2910265View Answer on Stackoverflow
Solution 24 - JavacnmucView Answer on Stackoverflow
Solution 25 - JavaAmar MagarView Answer on Stackoverflow
Solution 26 - JavaDmitriiView Answer on Stackoverflow
Solution 27 - JavaRabhi salimView Answer on Stackoverflow
Solution 28 - JavaMubasharView Answer on Stackoverflow
Solution 29 - JavaLiviu StirbView Answer on Stackoverflow
Solution 30 - JavaChristophe RoussyView Answer on Stackoverflow
Solution 31 - JavaAntonView Answer on Stackoverflow
Solution 32 - JavaPablo Santa CruzView Answer on Stackoverflow