Java: Check if enum contains a given string?

后端 未结 29 1309
一个人的身影
一个人的身影 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:39
      Set.of(CustomType.values())
         .contains(customTypevalue) 
    
    0 讨论(0)
  • 2020-12-02 04:40

    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.

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

    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.

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

    With guava it's even simpler:

    boolean isPartOfMyEnum(String myString){
    
    return Lists.newArrayList(MyEnum.values().toString()).contains(myString);
    
    }
    
    0 讨论(0)
  • 2020-12-02 04:41

    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;
    }
    
    0 讨论(0)
  • 2020-12-02 04:41
    public boolean contains(Choices value) {
       return EnumSet.allOf(Choices.class).contains(value);
    }
    
    0 讨论(0)
提交回复
热议问题