基于枚举常量的 Java 排序 [英] Java Sorting based on Enum constants

查看:32
本文介绍了基于枚举常量的 Java 排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个枚举

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 排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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