这是我的问题-我正在寻找(如果它甚至存在)等价于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
其他回答
我会写,
Arrays.stream(Choice.values()).map(Enum::name).collect(Collectors.toList()).contains("a1");
Enum#equals只适用于对象比较。
更好的是:
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;
}
};
如果你使用的是Java 8或以上版本,你可以这样做:
boolean isPresent(String testString){
return Stream.of(Choices.values()).map(Enum::name).collect(Collectors.toSet()).contains(testString);
}
EnumUtils。如果你想导入Apache commons lang3, isValidEnum可能是最好的选择。如果不是下面是一个通用函数,我会用作替代。
private <T extends Enum<T>> boolean enumValueExists(Class<T> enumType, String value) {
boolean result;
try {
Enum.valueOf(enumType, value);
result = true;
} catch (IllegalArgumentException e) {
result = false;
}
return result;
}
然后像下面这样使用
if (enumValueExists(MyEnum.class, configValue)) {
// happy code
} else {
// angry code
}
它是一个枚举,这些都是常量值,所以如果它在switch语句中,它就像这样做:
case: val1
case: val2
还有,为什么你需要知道什么被声明为常数?