trying to find an element by its constant parameter/field value(i.e. value0/value1/value2) without iterarting; is there a way? found guava utility method which works for enum constant name(i.e. CONSTANT0/CONSTANT1/CONSTANT2) and not parameter/field value to that name.
import com.google.common.base.Enums;
enum Enum {
CONSTANT0("value0"), CONSTANT1("value1"), CONSTANT2("value2");
private final String value;
Enum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
public class Driver {
public static void main(String[] args) {
// prints when input is value0
for (Enum constant : Enum.values()) {
if (constant.getValue().equalsIgnoreCase(args[0])) {
System.out
.println("vanilla version works with value i.e. java Driver value0"
+ args[0]);
}
}
// prints when input is CONSTANT0
if (Enums.getIfPresent(Enum.class, args[0]).isPresent())
System.out
.println("guava version works with constant i.e. java Driver CONSTANT0"
+ args[0]);
}
}
No.
Enums were designed and introduced in Java 1.5 in order to allow developers to enumerate their constants in a cleaner way. If you look at the
Enum.java
source, you won't see any easy look-up method similar to that of a hash-map. For code-clarity, if you want to check if your enum contains a value, without having to iterate at every use-case, you should create a static method which iterates over the contents of your enum.Please let me know if you have any questions!