den*_*chr 12 java sorting enums alphabetical comparator
我有一个类似以下的枚举类:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
稍后我的代码我基本上迭代了字母枚举并将其成员打印到控制台:
for (Letter letter : Letter.values()) {
System.out.println(letter.getDescription());
}
Run Code Online (Sandbox Code Playgroud)
我认为values()方法会给我一个enum的有序视图(如这里所提到的),但这不是这里的情况.我只是按照我在Letter枚举类中创建它们的顺序获取枚举成员.有没有办法按字母顺序输出枚举值?我需要一个单独的比较器对象,还是有内置的方法来做到这一点?基本上我希望根据getDescription()文本按字母顺序对值进行排序:
Alpha
Beta
Gamma
Omega
Run Code Online (Sandbox Code Playgroud)
mer*_*ike 21
SortedMap<String, Letter> map = new TreeMap<String, Letter>();
for (Letter l : Letter.values()) {
map.put(l.getDescription, l);
}
return map.values();
Run Code Online (Sandbox Code Playgroud)
或者只是重新排序声明:-)
编辑:正如KLE指出的那样,这假设描述在枚举中是唯一的.
我认为values()方法会给我一个enum的有序视图(如这里所提到的),但这不是这里的情况.我只是按照我在Letter枚举类中创建它们的顺序获取枚举成员.
确切地说,声明的顺序对于枚举来说是重要的,所以我们很高兴它们按照这个顺序返回.例如,当a int i表示枚举值时,执行操作values()[i]是查找枚举实例的一种非常简单有效的方法.相反,该ordinal()方法返回枚举实例的索引.
有没有办法按字母顺序输出枚举值?我需要一个单独的比较器对象,还是有内置的方法来做到这一点?基本上我希望根据getDescription()文本按字母顺序对值进行排序:
你所谓的价值不是一般为枚举定义的东西.在这里,在您的上下文中,您的意思是结果getDescription().
如您所说,您可以为这些描述创建一个Comparator.那将是完美的:-)
请注意,通常,您可能需要为这些实例提供多个订单:
你也可以稍微推动一下DescriptionComparator的概念:
出于性能原因,您可以存储计算的描述.
因为枚举不能继承,所以代码重用必须在枚举类之外.让我举一个我们将在项目中使用的例子:
现在代码示例......
/** Interface for enums that have a description. */
public interface Described {
/** Returns the description. */
String getDescription();
}
public enum Letter implements Described {
// .... implementation as in the original post,
// as the method is already implemented
}
public enum Other implements Described {
// .... same
}
/** Utilities for enums. */
public abstract class EnumUtils {
/** Reusable Comparator instance for Described objects. */
public static Comparator<Described> DESCRIPTION_COMPARATOR =
new Comparator<Described>() {
public int compareTo(Described a, Described b) {
return a.getDescription().compareTo(b.getDescription);
}
};
/** Return the sorted descriptions for the enum. */
public static <E extends Enum & Described> List<String>
getSortedDescriptions(Class<E> enumClass) {
List<String> descriptions = new ArrayList<String>();
for(E e : enumClass.getEnumConstants()) {
result.add(e.getDescription());
}
Collections.sort(descriptions);
return descriptions;
}
}
// caller code
List<String> letters = EnumUtils.getSortedDescriptions(Letter.class);
List<String> others = EnumUtils.getSortedDescriptions(Other.class);
Run Code Online (Sandbox Code Playgroud)
请注意,通用代码EnumUtils不仅适用于一个枚举类,而且适用于项目中实现该Described接口的任何枚举类.
如前所述,将代码置于枚举之外(否则将属于其中)的重点是重用代码.对于两个枚举而言,这并不是什么大不了的事,但我们的项目中有超过一千个枚举,其中许多具有相同的接口......!