这是我的问题-我正在寻找(如果它甚至存在)等价于ArrayList.contains();的enum。

下面是我的代码问题示例:

enum choices {a1, a2, b1, b2};

if(choices.???(a1)}{
//do this
} 

现在,我意识到字符串的数组列表在这里是更好的路由,但我必须通过其他地方的开关/case运行我的enum内容。这就是我的问题所在。

假设这样的东西不存在,我该怎么做呢?


当前回答

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

其他回答

虽然迭代一个列表或捕捉一个异常对于大多数情况来说已经足够好了,但我正在寻找一些可重用的东西,这些东西对于大型枚举来说也很好。最后,我写下了这样一段话:

public class EnumValidator {

    private final Set<String> values;

    private EnumValidator(Set<String> values) {
        this.values = values;
    }

    public static <T extends Enum<T>> EnumValidator of(Class<T> enumType){
        return new EnumValidator(Stream.of(enumType.getEnumConstants()).map(Enum::name).collect(Collectors.toSet()));
    }

    public boolean isPresent(String et){
        return values.contains(et);
    }
    
}

Java Streams提供了一种优雅的方式来做到这一点

Stream.of(MyEnum.values()).anyMatch(v -> v.name().equals(strValue))

返回: 如果流中的任何元素与提供的值匹配,则为True,否则为false

枚举在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;
  } 

};

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

你可以把它作为一个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
}