Java: Check if enum contains a given string?

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

提交回复
热议问题