Java: Check if enum contains a given string?

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

提交回复
热议问题