这是我的问题-我正在寻找(如果它甚至存在)等价于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内容。这就是我的问题所在。
假设这样的东西不存在,我该怎么做呢?
当前回答
Set.of(CustomType.values())
.contains(customTypevalue)
其他回答
你也可以使用:com.google.common.base.Enums
enumes . getifpresent (varEnum.class, varToLookFor)返回一个Optional
enumes . getifpresent (fooenumer .class, myVariable).isPresent() ? Enums.getIfPresent (fooEnum.class myVariable)。get: fooEnum。其他人
一些假设: 1)没有尝试/捕捉,因为它是特殊的流量控制 2)“包含”方法必须是快速的,因为它通常运行几次。 3)空间不受限制(普通解决方案常见)
import java.util.HashSet;
import java.util.Set;
enum Choices {
a1, a2, b1, b2;
private static Set<String> _values = new HashSet<>();
// O(n) - runs once
static{
for (Choices choice : Choices.values()) {
_values.add(choice.name());
}
}
// O(1) - runs several times
public static boolean contains(String value){
return _values.contains(value);
}
}
请使用Apache commons lang3库
EnumUtils.isValidEnum(MyEnum.class, myValue)
如果你使用的是Java 8或以上版本,你可以这样做:
boolean isPresent(String testString){
return Stream.of(Choices.values()).map(Enum::name).collect(Collectors.toSet()).contains(testString);
}
com.google.common.collect.Sets.newHashSet(MyEnum.values()).contains("myValue")