简体   繁体   中英

Java: Check if enum contains a given string?

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?

改用 Apache commons lang3 库

 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.

If the enum is very large you could stick the values in a HashSet:如果枚举非常大,您可以将值粘贴在 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.

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.

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

Guavas Enums could be your friend

Like eg this:

enum MyData {
    ONE,
    TWO
}

@Test
public void test() {

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

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;
  } 

};

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
}

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

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);
    }
}

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.

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

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.

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;
        }
}

如果您正在使用Apache Commons(或愿意这样做),则可以使用以下命令进行检查:

ArrayUtils.contains(choices.values(), value)

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");

这个对我有用:

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

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);
}

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
}

I would just write,

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

Enum#equals only works with object compare.

With guava it's even simpler:

boolean isPartOfMyEnum(String myString){

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

}

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));
    }
}

}

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

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;
}

如果你想通过字符串查找,你可以使用valueOf("a1")

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?

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);
}
  Set.of(CustomType.values())
     .contains(customTypevalue) 

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

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
}

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);
    }
    
}

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);
    ...
public boolean contains(Choices value) {
   return EnumSet.allOf(Choices.class).contains(value);
}

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;
  } 

};

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