peter.murray.rust peter.murray.rust - 5 months ago 30
Java Question

How can I lookup a Java enum from its String value?

I would like to lookup an enum from its string value (or possibly any other value). I've tried the following code but it doesn't allow static in initialisers. Is there a simple way?

public enum Verbosity {

BRIEF, NORMAL, FULL;

private static Map<String, Verbosity> stringMap = new HashMap<String, Verbosity>();

private Verbosity() {
stringMap.put(this.toString(), this);
}

public static Verbosity getVerbosity(String key) {
return stringMap.get(key);
}
};

Answer

Use the valueOf method which is automatically created for each Enum.

Verbosity.valueOf("BRIEF") == Verbosity.BRIEF

For arbitrary values start with:

public static Verbosity findByAbbr(String abbr){
    for(Verbosity v : values()){
        if( v.abbr().equals(abbr)){
            return v;
        }
    }
    return null;
}

Only move on later to Map implementation if your profiler tells you to.

I know it's iterating over all the values, but with only 3 enum values it's hardly worth any other effort, in fact unless you have a lot of values I wouldn't bother with a Map it'll be fast enough.

Comments