如何在Java中按字母顺序排列枚举成员? [英] How do I sort enum members alphabetically in Java?

查看:204
本文介绍了如何在Java中按字母顺序排列枚举成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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;
}
}

稍后我的代码我基本上迭代了字母枚举并将其成员打印到控制台:

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

我以为values()方法会给我一个有序的视图枚举(如 here 所述),但这不是这里的情况。我只是按照我在Letter枚举类中创建的顺序获取枚举成员。有没有办法按字母顺序输出枚举值?我需要一个单独的比较对象,还是有内置的方式来做到这一点?基本上我希望按照getDescription()文本按字母顺序排序值:

  Alpha 
Beta
Gamma
欧米茄


解决方案

  SortedMap< String,Letter> map = new TreeMap< String,Letter>(); 
(Letter l:Letter.values()){
map.put(l.getDescription,l);
}
return map.values();

或者只是重新排序声明: - )



编辑:正如KLE指出的那样,这假设说明在枚举中是唯一的。


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

解决方案

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.

这篇关于如何在Java中按字母顺序排列枚举成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆