这是我的问题-我正在寻找(如果它甚至存在)等价于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 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);
...
其他回答
番石榴可以成为你的朋友
比如这个:
enum MyData {
ONE,
TWO
}
@Test
public void test() {
if (!Enums.getIfPresent(MyData.class, "THREE").isPresent()) {
System.out.println("THREE is not here");
}
}
这结合了以前方法中的所有方法,应该具有相同的性能。它可以用于任何枚举,内联“编辑”解决方案从@Richard H,并使用例外的无效值,如@bestsss。唯一的折衷是需要指定类,但这将把它变成一个两行代码。
import java.util.EnumSet;
public class HelloWorld {
static enum Choices {a1, a2, b1, b2}
public static <E extends Enum<E>> boolean contains(Class<E> _enumClass, String value) {
try {
return EnumSet.allOf(_enumClass).contains(Enum.valueOf(_enumClass, value));
} catch (Exception e) {
return false;
}
}
public static void main(String[] args) {
for (String value : new String[] {"a1", "a3", null}) {
System.out.println(contains(Choices.class, value));
}
}
}
枚举在Java中非常强大。你可以很容易地在枚举中添加contains方法(就像在类中添加方法一样):
enum choices {
a1, a2, b1, b2;
public boolean contains(String s)
{
if (s.equals("a1") || s.equals("a2") || s.equals("b1") || s.equals("b2"))
return true;
return false;
}
};
这里已经提到了几个库,但是我错过了我真正要找的一个:Spring!
ObjectUtils#containsConstant默认情况下是不区分大小写的,但如果你愿意,可以严格设置。它是这样使用的:
if(ObjectUtils.containsConstant(Choices.values(), "SOME_CHOISE", true)){
// do stuff
}
注意:我在这里使用重载方法是为了演示如何使用区分大小写的检查。您可以省略布尔值以具有不区分大小写的行为。
但是要小心使用大的枚举,因为他们不像一些人那样使用Map实现…
作为奖励,它还提供了valueOf的大小写不敏感变体:ObjectUtils#caseInsensitiveValueOf
你也可以使用:com.google.common.base.Enums
enumes . getifpresent (varEnum.class, varToLookFor)返回一个Optional
enumes . getifpresent (fooenumer .class, myVariable).isPresent() ? Enums.getIfPresent (fooEnum.class myVariable)。get: fooEnum。其他人