Java: Check if enum contains a given string?

匿名 (未验证) 提交于 2019-12-03 01:29:01

问题:

Here's my problem...I'm looking for (if it even exists) the enum equivalent of ArrayList.contains();.

Here's a sample of my code problem:

enum choices {a1, a2, b1, b2};  if(choices.???(a1)}{ //do this } 

Now, I realize that an ArrayList of Strings would be the better route here but I have to run my enum contents through a switch/case elsewhere. Hence my problem.

Assuming something like this doesn't exist, how could I go about doing it?

Thanks!

回答1:

This should do it:

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

This way means you do not have to worry about adding additional enum values later, they are all checked.

Edit: If the enum is very large you could stick the values in a HashSet:

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

Then you can just do: values.contains("your string") which returns true or false.



回答2:

Use the Apache commons lang3 lib instead

 EnumUtils.isValidEnum(MyEnum.class, myValue)


回答3:

You can use 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   } }

If you expect the check to fail often, you might be better off using a simple loop as other have shown - if your enums contain many values, perhaps builda HashSet or similar of your enum values converted to a string and query that HashSet instead,



回答4:

Guavas Enums could be your friend

Like e.g. this:

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


回答5:

Even better:

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


回答6:

If you are using Java 1.8, you can choose Stream + Lambda to implement this:

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        
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!