这是我的问题-我正在寻找(如果它甚至存在)等价于ArrayList.contains();的enum。
下面是我的代码问题示例:
enum choices {a1, a2, b1, b2};
if(choices.???(a1)}{
//do this
}
现在,我意识到字符串的数组列表在这里是更好的路由,但我必须通过其他地方的开关/case运行我的enum内容。这就是我的问题所在。
假设这样的东西不存在,我该怎么做呢?
这是我的问题-我正在寻找(如果它甚至存在)等价于ArrayList.contains();的enum。
下面是我的代码问题示例:
enum choices {a1, a2, b1, b2};
if(choices.???(a1)}{
//do this
}
现在,我意识到字符串的数组列表在这里是更好的路由,但我必须通过其他地方的开关/case运行我的enum内容。这就是我的问题所在。
假设这样的东西不存在,我该怎么做呢?
当前回答
Java Streams提供了一种优雅的方式来做到这一点
Stream.of(MyEnum.values()).anyMatch(v -> v.name().equals(strValue))
返回: 如果流中的任何元素与提供的值匹配,则为True,否则为false
其他回答
你可以使用enumenumeof ()
enum Choices{A1, A2, B1, B2};
public class MainClass {
public static void main(String args[]) {
Choices day;
try {
day = Choices.valueOf("A1");
//yes
} catch (IllegalArgumentException ex) {
//nope
}
}
如果你希望检查经常失败,你可能会更好地使用一个简单的循环,就像其他人展示的那样——如果你的枚举包含很多值,可能会将一个HashSet或类似的枚举值转换为字符串并查询该HashSet。
如果你使用的是Java 8或以上版本,你可以这样做:
boolean isPresent(String testString){
return Stream.of(Choices.values()).map(Enum::name).collect(Collectors.toSet()).contains(testString);
}
我会写,
Arrays.stream(Choice.values()).map(Enum::name).collect(Collectors.toList()).contains("a1");
Enum#equals只适用于对象比较。
你也可以使用:com.google.common.base.Enums
enumes . getifpresent (varEnum.class, varToLookFor)返回一个Optional
enumes . getifpresent (fooenumer .class, myVariable).isPresent() ? Enums.getIfPresent (fooEnum.class myVariable)。get: fooEnum。其他人
我不认为有,但你可以这样做:
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这样做。