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:
<
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(Period.valueOf("DAILY")::equals);
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;
}
};
This one works for me:
Arrays.asList(YourEnum.values()).toString().contains("valueToCheck");
Few assumptions:
1) No try/catch, as it is exceptional flow control
2) 'contains' method has to be quick, as it usually runs several times.
3) Space is not limited (common for ordinary solutions)
import java.util.HashSet;
import java.util.Set;
enum Choices {
a1, a2, b1, b2;
private static Set<String> _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);
}
}
com.google.common.collect.Sets.newHashSet(MyEnum.values()).contains("myValue")
Use the Apache commons lang3 lib instead
EnumUtils.isValidEnum(MyEnum.class, myValue)