I was recently defining an enum with some keys. But the enum needed more than a key. It also needed a configuration parameter that would define if this key has some special feature avaliable.
So I defined the enum with a constructor that had 2 inputs, the key and the configuration boolean attribute.
Now the question was, how to find the enum for the key. And here I am going to exactly show the code that does it.
import java.util.HashMap;
import java.util.Map;
public enum MyEnum {
KEY1 ("key1", false),
KEY2 ("key2", false);
private final String key;
private final boolean featureAvailable;
private static final Map<String, MyEnum> LABEL_MAP = new HashMap<>();
static {
for (MyEnum enumVal : MyEnum.values()) {
LABEL_MAP.put(enumVal.getKey(), enumVal);
}
}
private MyEnum(String key, boolean featureAvailable) {
this.key = key;
this.featureAvailable = featureAvailable;
}
public static MyEnum getEnumFromLabel(String label) {
return LABEL_MAP.get(label);
}
public boolean isFeatureAvailable() {
return featureAvailable;
}
public String getKey() {
return key;
}
}
Now from the above class you can use getEnumFromLabel to get the enum from the label.
Here is a little better version of the Map. The below code makes sure that the keys are not duplicated. Any duplicate would raise an error.
static {
for (MyEnum enumVal : MyEnum.values()) {
if(LABEL_MAP.containsKey(enumVal.getKey())) {
throw new IllegalStateException("Duplicate Keys for enums: " + enumVal + " : " + LABEL_MAP.get(enumVal.getKey()));
}
LABEL_MAP.put(enumVal.getKey(), enumVal);
}
}
And here is the test to show, how the above code can help improve the enum implementation
import java.util.HashMap;
import java.util.Map;
public enum MyEnum {
KEY1 ("key1", false),
KEY2 ("key2", false),
KEY3 ("key2", false);
private final String key;
private final boolean featureAvailable;
private static final Map<String, MyEnum> LABEL_MAP = new HashMap<>();
static {
for (MyEnum enumVal : MyEnum.values()) {
if(LABEL_MAP.containsKey(enumVal.getKey())) {
throw new IllegalStateException("Duplicate Keys for enums: " + enumVal + " : " + LABEL_MAP.get(enumVal.getKey()));
}
LABEL_MAP.put(enumVal.getKey(), enumVal);
}
}
private MyEnum(String key, boolean featureAvailable) {
this.key = key;
this.featureAvailable = featureAvailable;
}
public static MyEnum getEnumFromLabel(String label) {
return LABEL_MAP.get(label);
}
public boolean isFeatureAvailable() {
return featureAvailable;
}
public String getKey() {
return key;
}
public static void main(String[] args) {
for (MyEnum enumVal : MyEnum.values()) {
System.out.println(enumVal.getKey() + " : " + getEnumFromLabel(enumVal.getKey()));
}
}
}
You can run the above code and see that it doesn’t run. It throws an error with duplicate Key.