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:
enum choices {a1, a2, b1, b2};
if(choices.???(a1)}{
//do this
}
Now, I realize that an ArrayList
of Strings
would be the better route here but I have to run my enum contents through a switch/case elsewhere. Hence my problem.
Assuming something like this doesn't exist, how could I go about doing it?
You can use Enum.valueOf()
enum Choices{A1, A2, B1, B2};
public class MainClass {
public static void main(String args[]) {
Choices day;
try {
day = Choices.valueOf("A1");
//yes
} catch (IllegalArgumentException ex) {
//nope
}
}
If you expect the check to fail often, you might be better off using a simple loop as other have shown - if your enums contain many values, perhaps builda HashSet
or similar of your enum values converted to a string and query that HashSet
instead.
You can make it as a contains method:
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;
}
}
or you can just use it with your code block:
try{
EnumSet.allOf(choices.class).contains(Enum.valueOf(choices.class, "a1"));
//do something
}catch (Exception e) {
//do something else
}
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);
}
Set.of(CustomType.values())
.contains(customTypevalue)
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);
}
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")
A couple libraries have been mentioned here, but I miss the one that I was actually looking for: Spring!
There is the ObjectUtils#containsConstant which is case insensitive by default, but can be strict if you want. It is used like this:
if(ObjectUtils.containsConstant(Choices.values(), "SOME_CHOISE", true)){
// do stuff
}
Note: I used the overloaded method here to demonstrate how to use case sensitive check. You can omit the boolean to have case insensitive behaviour.
Be careful with large enums though, as they don't use the Map implementation as some do...
As a bonus, it also provides a case insensitive variant of the valueOf: ObjectUtils#caseInsensitiveValueOf
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;
}
};
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
}
public boolean contains(Choices value) {
return EnumSet.allOf(Choices.class).contains(value);
}
Use the Apache commons lang3 lib instead
EnumUtils.isValidEnum(MyEnum.class, myValue)
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.
EnumUtils.isValidEnum
might be the best option if you like to import Apache commons lang3. if not following is a generic function I would use as an alternative.
private <T extends Enum<T>> boolean enumValueExists(Class<T> enumType, String value) {
boolean result;
try {
Enum.valueOf(enumType, value);
result = true;
} catch (IllegalArgumentException e) {
result = false;
}
return result;
}
And use it as following
if (enumValueExists(MyEnum.class, configValue)) {
// happy code
} else {
// angry code
}
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.
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 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");
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");
}
}
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;
}
}
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));
}
}
}
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);
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;
}
enum
are pretty powerful in Java. You could easily add a contains
method to your enum (as you would add a method to a class):
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;
}
};
With guava it's even simpler:
boolean isPartOfMyEnum(String myString){
return Lists.newArrayList(MyEnum.values().toString()).contains(myString);
}
I would just write,
Arrays.stream(Choice.values()).map(Enum::name).collect(Collectors.toList()).contains("a1");
Enum#equals only works with object compare.
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
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
You can use valueOf("a1")
if you want to look up by String
Source: Stackoverflow.com