问题描述
我们有一个枚举
enum listE {
LE1,
LE4,
LE2,
LE3
}
此外,我们有一个包含字符串 ["LE1","LE2","LE3","LE4"]
的列表.有没有办法根据枚举定义的顺序(不是自然的 String
顺序)对列表进行排序.
Furthermore, we have a list that contains the strings ["LE1","LE2","LE3","LE4"]
. Is there a way to sort the list based on the enum defined order (not the natural String
order).
排序后的列表应该是["LE1", "LE4", "LE2", "LE3"]
.
推荐答案
Enum
通过枚举的自然顺序(声明值的顺序)实现 Comparable
.如果您只是通过解析创建一个枚举值列表(而不是字符串),然后使用 Collections.sort
对该列表进行排序,它应该按照您想要的方式排序.如果你再次需要一个字符串列表,你可以通过在每个元素上调用 name()
来转换回来.
Enum<E>
implements Comparable<E>
via the natural order of the enum (the order in which the values are declared). If you just create a list of the enum values (instead of strings) via parsing, then sort that list using Collections.sort
, it should sort the way you want. If you need a list of strings again, you can just convert back by calling name()
on each element.
这篇关于基于枚举常量的 Java 排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!