tags:

views:

2090

answers:

3

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);
 }
};
+2  A: 

And you can't use valueOf()?

Edit: Btw, there is nothing stopping you from using static { } in an enum.

Fredrik
Or the synthetic `valueOf` on the enum class, so you don't need to specify the enum class `Class`.
Tom Hawtin - tackline
Of course, it just didn't have a javadoc entry so it was hard to link to.
Fredrik
you can link to the JLS: http://java.sun.com/docs/books/jls/third_edition/html/classes.html#302265
newacct
Fixed, thank you.
Fredrik
+2  A: 

You're close. For arbitrary values, try something like the following:

   public enum Day { 
        MONDAY("M"), TUESDAY("T"), WEDNESDAY("W"),
        THURSDAY("R"), FRIDAY("F"), SATURDAY("Sa"), SUNDAY("Su"), ;

        private final String abbreviation;
        // Reverse-lookup map for getting a day from an abbreviation
        private static final Map<String, Day> lookup = new HashMap<String, Day>();
        static {
            for (Day d : Day.values())
                lookup.put(d.getAbbreviation(), d);
        }

        private Day(String abbreviation) {
            this.abbreviation = abbreviation;
        }

        public String getAbbreviation() {
            return abbreviation;
        }

        public static Day get(String abbreviation) {
            return lookup.get(abbreviation);
        }
    }
Lyle
instead of "EnumSet.allOf(Day.class)" you can use "Day.values()"...
Carlos Heuberger
Ah, so I can. Thanks.
Lyle
+12  A: 

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

Verbosity.valueOf("BRIEF") == Verbority.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;
}

And 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.

Gareth Davis
thanks - and I can use case conversion if I know the values are still distinct
peter.murray.rust