Java: Check if enum contains a given string?

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

    Java Streams provides elegant way to do that

    Stream.of(MyEnum.values()).anyMatch(v -> v.name().equals(strValue))
    

    Returns: true if any elements of the stream match the provided value, otherwise false

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

    It is an enum, those are constant values so if its in a switch statement its just doing something like this:

    case: val1
    case: val2
    

    Also why would you need to know what is declared as a constant?

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

    This combines all of the approaches from previous methods and should have equivalent performance. It can be used for any enum, inlines the "Edit" solution from @Richard H, and uses Exceptions for invalid values like @bestsss. The only tradeoff is that the class needs to be specified, but that turns this into a two-liner.

    import java.util.EnumSet;
    
    public class HelloWorld {
    
    static enum Choices {a1, a2, b1, b2}
    
    public static <E extends Enum<E>> boolean contains(Class<E> _enumClass, String value) {
        try {
            return EnumSet.allOf(_enumClass).contains(Enum.valueOf(_enumClass, value));    
        } catch (Exception e) {
            return false; 
        }
    }
    
    public static void main(String[] args) {
        for (String value : new String[] {"a1", "a3", null}) {
            System.out.println(contains(Choices.class, value));
        }
    }
    

    }

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

    Why not combine Pablo's reply with a valueOf()?

    public enum Choices
    {
        a1, a2, b1, b2;
    
        public static boolean contains(String s) {
            try {
                Choices.valueOf(s);
                return true;
            } catch (Exception e) {
                return false;
            }
    }
    
    0 讨论(0)
  • 2020-12-02 04:45

    you can also use : com.google.common.base.Enums

    Enums.getIfPresent(varEnum.class, varToLookFor) returns an Optional

    Enums.getIfPresent(fooEnum.class, myVariable).isPresent() ? Enums.getIfPresent(fooEnum.class, myVariable).get : fooEnum.OTHERS

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

    This approach can be used to check any Enum, you can add it to an Utils class:

    public static <T extends Enum<T>> boolean enumContains(Class<T> enumerator, String value)
    {
        for (T c : enumerator.getEnumConstants()) {
            if (c.name().equals(value)) {
                return true;
            }
        }
        return false;
    }
    

    Use it this way:

    boolean isContained = Utils.enumContains(choices.class, "value");
    
    0 讨论(0)
提交回复
热议问题