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

查看:474
本文介绍了基于枚举常量进行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]

推荐答案

枚举< E> 通过枚举的自然顺序实现 Comparable< E> 值被声明)。如果您只需通过解析创建枚举值列表(而不是字符串),则使用 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天全站免登陆