Java: Check if enum contains a given string?

后端 未结 29 1307
一个人的身影
一个人的身影 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:48

    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);
    
    0 讨论(0)
  • 2020-12-02 04:48

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

    This one works for me:

    Arrays.asList(YourEnum.values()).toString().contains("valueToCheck");
    
    0 讨论(0)
  • 2020-12-02 04:50

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-02 04:50
    com.google.common.collect.Sets.newHashSet(MyEnum.values()).contains("myValue")
    
    0 讨论(0)
  • 2020-12-02 04:54

    Use the Apache commons lang3 lib instead

     EnumUtils.isValidEnum(MyEnum.class, myValue)
    
    0 讨论(0)
提交回复
热议问题