Convert from String to a Java enum with large amount of values
This question already has an answer here:
You want a Map<String, Code>
, but how to populate it neatly? Enums don't allow you to initialize a static fields before the enum instances are initialized, but there's a neat little trick, called the Initialization-on-demand holder idiom, that makes using a statically initialized map needed for this functionality easy to implement:
public enum Code {
CODE_1("string1"),
CODE_2("string2"),
CODE_3("string3"),
// etc
;
private static class Holder {
static Map<String, Code> CODE_MAP = new HashMap<>();
}
private final String code;
private Code(String code) {
this.code = code;
Holder.CODE_MAP.put(code, this);
}
public String getCode() {
return this.code;
}
public Code convertFromString(String code) {
return CODE_MAP.get(code);
}
}
This works because the class loader initializes inner static classes before initializing the enum class, so the map is assigned ready to load during enum instance initialization.
No loops. No special code to load the map (done in constructor). Minimal code.
Map is good option : cleaner code and O(1)
. If you use for-loop
then the best you get is O(n)
Your provided solution is proper implementation.
As you will have to expose only one method and it is more readable.
And it is always good to use Map
instead of iterating it manually
.
And also as you mentioned the complexity is O(1)
.
+1 to your question
, as it gives a cleaner approach to use enum in some usecases
.
上一篇: 将字符串转换为枚举?