这是我的问题-我正在寻找(如果它甚至存在)等价于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内容。这就是我的问题所在。
假设这样的东西不存在,我该怎么做呢?
当前回答
您可以先将枚举转换为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
}
其他回答
如果你使用的是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 contains(String s)
{
for(choices choice:values())
if (choice.name().equals(s))
return true;
return false;
}
};
你可以用这个
YourEnum {A1, A2, B1, B2}
boolean contains(String str){
return Sets.newHashSet(YourEnum.values()).contains(str);
}
@wightwulf1944建议的更新被纳入,使解决方案更有效。
你可以把它作为一个contains方法:
enum choices {a1, a2, b1, b2};
public boolean contains(String value){
try{
EnumSet.allOf(choices.class).contains(Enum.valueOf(choices.class, value));
return true;
}catch (Exception e) {
return false;
}
}
或者你可以在代码块中使用它:
try{
EnumSet.allOf(choices.class).contains(Enum.valueOf(choices.class, "a1"));
//do something
}catch (Exception e) {
//do something else
}
这里已经提到了几个库,但是我错过了我真正要找的一个:Spring!
ObjectUtils#containsConstant默认情况下是不区分大小写的,但如果你愿意,可以严格设置。它是这样使用的:
if(ObjectUtils.containsConstant(Choices.values(), "SOME_CHOISE", true)){
// do stuff
}
注意:我在这里使用重载方法是为了演示如何使用区分大小写的检查。您可以省略布尔值以具有不区分大小写的行为。
但是要小心使用大的枚举,因为他们不像一些人那样使用Map实现…
作为奖励,它还提供了valueOf的大小写不敏感变体:ObjectUtils#caseInsensitiveValueOf