How do I sort enum members alphabetically in Java?

denchr picture denchr · Nov 14, 2009 · Viewed 25.2k times · Source

I have an enum class like the following:

public enum Letter {
    OMEGA_LETTER("Omega"), 
    GAMMA_LETTER("Gamma"), 
    BETA_LETTER("Beta"), 
    ALPHA_LETTER("Alpha"), 

    private final String description;

    Letter() {
      description = toString();
    }

    Letter(String description) {
      this.description = description;
    }

    public String getDescription() {
      return description;
    }
}

Later down my code I basically iterate over the Letter enum and print its members out to the console:

for (Letter letter : Letter.values()) {
System.out.println(letter.getDescription());
}

I thought that the values() method would give me an ordered view of the enum (as mentioned here), but this is not the case here. I simply get the enum members in the order I created them within the Letter enum class. Is there a way to output the values of an enum in alphabetical order? Would I need a separate comparator object, or is there a built-in way to do this? Basically I would like the values to be alphabetically sorted based on the getDescription() text:

Alpha
Beta
Gamma
Omega

Answer

meriton picture meriton · Nov 14, 2009
SortedMap<String, Letter> map = new TreeMap<String, Letter>();
for (Letter l : Letter.values()) {
    map.put(l.getDescription, l);
}
return map.values();

Or just reorder the declarations :-)

Edit: As KLE pointed out, this assumes that the Descriptions are unique within the enum.