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

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

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

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

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

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


当前回答

你也可以使用:com.google.common.base.Enums

enumes . getifpresent (varEnum.class, varToLookFor)返回一个Optional

enumes . getifpresent (fooenumer .class, myVariable).isPresent() ? Enums.getIfPresent (fooEnum.class myVariable)。get: fooEnum。其他人

其他回答

你可以用这个

YourEnum {A1, A2, B1, B2}

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

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

Java 8+流+设置方式:

    // Build the set.
    final Set<String> mySet = Arrays//
      .stream(YourEnumHere.values())//
      .map(Enum::name)//
      .collect(Collectors.toSet());

    // Reuse the set for contains multiple times.
    mySet.contains(textA);
    mySet.contains(textB);
    ...

我会写,

Arrays.stream(Choice.values()).map(Enum::name).collect(Collectors.toList()).contains("a1");

Enum#equals只适用于对象比较。

  Set.of(CustomType.values())
     .contains(customTypevalue) 

您可以先将枚举转换为List,然后使用List contains方法

enum Choices{A1, A2, B1, B2};

List choices = Arrays.asList(Choices.values());

//compare with enum value 
if(choices.contains(Choices.A1)){
   //do something
}

//compare with String value
if(choices.contains(Choices.valueOf("A1"))){
   //do something
}