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:
<
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<String> getEnums() {
HashSet<String> values = new HashSet<String>();
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.
You can use valueOf("a1")
if you want to look up by String
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");
}
}
You can first convert the enum to List and then use list contains method
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
}
I created the next class for this validation
public class EnumUtils {
public static boolean isPresent(Enum enumArray[], String name) {
for (Enum element: enumArray ) {
if(element.toString().equals(name))
return true;
}
return false;
}
}
example of usage :
public ArrivalEnum findArrivalEnum(String name) {
if (!EnumUtils.isPresent(ArrivalEnum.values(), name))
throw new EnumConstantNotPresentException(ArrivalEnum.class,"Arrival value must be 'FROM_AIRPORT' or 'TO_AIRPORT' ");
return ArrivalEnum.valueOf(name);
}
If you are Using Java 8 or above, you can do this :
boolean isPresent(String testString){
return Stream.of(Choices.values()).map(Enum::name).collect(Collectors.toSet()).contains(testString);
}