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:
<
Java Streams provides elegant way to do that
Stream.of(MyEnum.values()).anyMatch(v -> v.name().equals(strValue))
Returns: true if any elements of the stream match the provided value, otherwise false
It is an enum, those are constant values so if its in a switch statement its just doing something like this:
case: val1
case: val2
Also why would you need to know what is declared as a constant?
This combines all of the approaches from previous methods and should have equivalent performance. It can be used for any enum, inlines the "Edit" solution from @Richard H, and uses Exceptions for invalid values like @bestsss. The only tradeoff is that the class needs to be specified, but that turns this into a two-liner.
import java.util.EnumSet;
public class HelloWorld {
static enum Choices {a1, a2, b1, b2}
public static <E extends Enum<E>> boolean contains(Class<E> _enumClass, String value) {
try {
return EnumSet.allOf(_enumClass).contains(Enum.valueOf(_enumClass, value));
} catch (Exception e) {
return false;
}
}
public static void main(String[] args) {
for (String value : new String[] {"a1", "a3", null}) {
System.out.println(contains(Choices.class, value));
}
}
}
Why not combine Pablo's reply with a valueOf()?
public enum Choices
{
a1, a2, b1, b2;
public static boolean contains(String s) {
try {
Choices.valueOf(s);
return true;
} catch (Exception e) {
return false;
}
}
you can also use : com.google.common.base.Enums
Enums.getIfPresent(varEnum.class, varToLookFor) returns an Optional
Enums.getIfPresent(fooEnum.class, myVariable).isPresent() ? Enums.getIfPresent(fooEnum.class, myVariable).get : fooEnum.OTHERS
This approach can be used to check any Enum
, you can add it to an Utils
class:
public static <T extends Enum<T>> boolean enumContains(Class<T> enumerator, String value)
{
for (T c : enumerator.getEnumConstants()) {
if (c.name().equals(value)) {
return true;
}
}
return false;
}
Use it this way:
boolean isContained = Utils.enumContains(choices.class, "value");