java判断枚举是否包含_Java:检查枚举是否包含给定的string?

这应该做到这一点:

public static boolean contains(String test) { for (Choice c : Choice.values()) { if (c.name().equals(test)) { return true; } } return false; }

这样的方式意味着你不必担心后面添加额外的枚举值,他们都被检查。

编辑:如果枚举非常大,您可以将值粘贴到HashSet中:

public static HashSet getEnums() { HashSet values = new HashSet(); for (Choice c : Choice.values()) { values.add(c.name()); } return values; }

然后你可以做: values.contains("your string") ,返回true或false。

改用Apache commons lang3 lib

EnumUtils.isValidEnum(MyEnum.class, myValue)

你可以使用Enum.valueOf

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 } }

如果你希望检查经常失败,你可能会更好的使用一个简单的循环,如其他人所示 – 如果你的枚举包含许多值,可能builda HashSet或类似的枚举值转换为一个string,并查询该HashSet,

番石榴引子可能是你的朋友

像这样:

enum MyData { ONE, TWO } @Test public void test() { if (!Enums.getIfPresent(MyData.class, "THREE").isPresent()) { System.out.println("THREE is not here"); } }

更好:

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 1.8,则可以selectStream + Lambda来实现此目的:

public enum Period { DAILY, WEEKLY }; //This is recommended Arrays.stream(Period.values()).anyMatch((t) -> t.name().equals("DAILY1")); //May throw java.lang.IllegalArgumentException Arrays.stream(Period.values()).anyMatch(Period.valueOf("DAILY")::equals);

我不认为有,但你可以做这样的事情:

enum choices {a1, a2, b1, b2}; public static boolean exists(choices choice) { for(choice aChoice : choices.values()) { if(aChoice == choice) { return true; } } return false; }

编辑:

请参阅理查德的版本,因为这样做更合适,除非您将其转换为使用Richards所使用的string。

如果您使用的是Apache Commons(或者愿意这样做),那么可以使用以下命令来检查它:

ArrayUtils.contains(choices.values(), value)

你可以使用这个

YourEnum {A1,A2,B1,B2}

boolean contains(String str){ return Sets.newHashSet(YourEnum.values()).contains(str); }

将@ wightwulf1944build议的更新结合起来使解决scheme更有效率。

几个假设:

1)没有尝试/捕捉,因为它是特殊的stream量控制

2)“包含”方法必须很快,因为它通常运行几次。

3)空间不限(普通的解决scheme)

import java.util.HashSet; import java.util.Set; enum Choices { a1, a2, b1, b2; private static Set _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); } }

您可以先将枚举转换为列表,然后使用列表包含方法

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 }

如果你想通过string查找,你可以使用valueOf("a1")

为什么不把巴勃罗的答复与valueOf()?

public enum Choices { a1, a2, b1, b2; public static boolean contains(String s) { try { Choices.valueOf(s); return true; } catch (Exception e) { return false; } }

这是一个枚举,那些是不变的值,所以如果它在switch语句中就是这样做的:

case: val1 case: val2

另外为什么你需要知道什么是一个常数声明?

public boolean contains(Choices value) { return EnumSet.allOf(Choices.class).contains(value); }

番石榴更简单:

boolean isPartOfMyEnum(String myString){ return Lists.newArrayList(MyEnum.values().toString()).contains(myString); }

这结合了以前方法的所有方法,并应具有相同的性能。 它可以用于任何枚举,从@Richard H内嵌“编辑”解决scheme,并使用例外作为@bestsss之类的无效值。 唯一的折衷是需要指定类,但是这将变成双线。

import java.util.EnumSet; public class HelloWorld { static enum Choices {a1, a2, b1, b2} public static > boolean contains(Class _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)); } }

}

com.google.common.collect.Sets.newHashSet(MyEnum.values()).contains("myValue")

这种方法可以用来检查任何Enum ,你可以将它添加到一个Utils类中:

public static > boolean enumContains(Class enumerator, String value) { for (T c : enumerator.getEnumConstants()) { if (c.name().equals(value)) { return true; } } return false; }

这样使用它:

boolean isContained = Utils.enumContains(choices.class, "value");

解决scheme检查值是否存在以及获取枚举值作为回报:

protected TradeType getEnumType(String tradeType) { if (tradeType != null) { if (EnumUtils.isValidEnum(TradeType.class, tradeType)) { return TradeType.valueOf(tradeType); } } return null; }

我的名声不需要评论,但我认为chaiyachaiya和帕布罗圣克鲁斯的答案是完全错误的。 首先,Enum用==操作符覆盖散列码,因为它的实例保证是单例,因此它不会比较操作数的逻辑相等。 这就是为什么如果我们使用MyEnum.values()并检查contains() ,我们将永远是false 。 其次, MyEnum.values().toString()将调用MyEnum类对象的toString() ,而不是MyEnum类的实例(如果在类的cause中覆盖此方法)。 那么,你将得到什么与Lists.newArrayList(MyEnum.values().toString()).contains(myString) ?

enum在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; } };

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值