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:
<
Set.of(CustomType.values())
.contains(customTypevalue)
I don't think there is, but you can do something like this:
enum choices {a1, a2, b1, b2};
public static boolean exists(choices choice) {
for(choice aChoice : choices.values()) {
if(aChoice == choice) {
return true;
}
}
return false;
}
Edit:
Please see Richard's version of this as it is more appropriate as this won't work unless you convert it to use Strings, which Richards does.
You can use this
YourEnum {A1, A2, B1, B2}
boolean contains(String str){
return Sets.newHashSet(YourEnum.values()).contains(str);
}
Update suggested by @wightwulf1944 is incorporated to make the solution more efficient.
With guava it's even simpler:
boolean isPartOfMyEnum(String myString){
return Lists.newArrayList(MyEnum.values().toString()).contains(myString);
}
solution to check whether value is present as well get enum value in return :
protected TradeType getEnumType(String tradeType) {
if (tradeType != null) {
if (EnumUtils.isValidEnum(TradeType.class, tradeType)) {
return TradeType.valueOf(tradeType);
}
}
return null;
}
public boolean contains(Choices value) {
return EnumSet.allOf(Choices.class).contains(value);
}