这是我的问题-我正在寻找(如果它甚至存在)等价于ArrayList.contains();的enum。

下面是我的代码问题示例:

enum choices {a1, a2, b1, b2};

if(choices.???(a1)}{
//do this
} 

现在,我意识到字符串的数组列表在这里是更好的路由,但我必须通过其他地方的开关/case运行我的enum内容。这就是我的问题所在。

假设这样的东西不存在,我该怎么做呢?


当前回答

如果你使用的是Java 8或以上版本,你可以这样做:

boolean isPresent(String testString){
      return Stream.of(Choices.values()).map(Enum::name).collect(Collectors.toSet()).contains(testString);
}

其他回答

我不认为有,但你可以这样做:

enum choices {a1, a2, b1, b2};

public static boolean exists(choices choice) {
   for(choice aChoice : choices.values()) {
      if(aChoice == choice) {
         return true;
      }
   }
   return false;
}

编辑:

请参阅Richard的版本,因为它更合适,因为这不会工作,除非你将它转换为使用字符串,Richards这样做。

Java Streams提供了一种优雅的方式来做到这一点

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

返回: 如果流中的任何元素与提供的值匹配,则为True,否则为false

更好的是:

enum choices {
   a1, a2, b1, b2;

  public static boolean contains(String s)
  {
      for(choices choice:values())
           if (choice.name().equals(s)) 
              return true;
      return false;
  } 

};

这结合了以前方法中的所有方法,应该具有相同的性能。它可以用于任何枚举,内联“编辑”解决方案从@Richard H,并使用例外的无效值,如@bestsss。唯一的折衷是需要指定类,但这将把它变成一个两行代码。

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));
    }
}

}

你可以用这个

YourEnum {A1, A2, B1, B2}

boolean contains(String str){ 
    return Sets.newHashSet(YourEnum.values()).contains(str);
}                                  

@wightwulf1944建议的更新被纳入,使解决方案更有效。