Java: Check if enum contains a given string?

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

    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.

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

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

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

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

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

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

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