Java: Check if enum contains a given string?

后端 未结 29 1308
一个人的身影
一个人的身影 2020-12-02 03:59

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:

<         


        
相关标签:
29条回答
  • 2020-12-02 04:54

    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.

    0 讨论(0)
  • 2020-12-02 04:56

    I would just write,

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

    Enum#equals only works with object compare.

    0 讨论(0)
  • 2020-12-02 05:00

    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

    0 讨论(0)
  • 2020-12-02 05:01

    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
    }
    
    
    0 讨论(0)
  • 2020-12-02 05:02

    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;
      } 
    
    };
    
    0 讨论(0)
提交回复
热议问题