Java基于Enum常量的排序

发布于 2024-12-13 19:08:25 字数 271 浏览 4 评论 0原文

我们有一个枚举

enum listE {
    LE1,
    LE4,
    LE2,
    LE3
}

此外,我们还有一个包含字符串["LE1","LE2","LE3","LE4"]的列表。有没有一种方法可以根据枚举定义的顺序(而不是自然的 String 顺序)对列表进行排序。

排序后的列表应为["LE1", "LE4", "LE2", "LE3"]

We have an enum

enum listE {
    LE1,
    LE4,
    LE2,
    LE3
}

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).

The sorted list should be ["LE1", "LE4", "LE2", "LE3"].

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

未蓝澄海的烟 2024-12-20 19:08:25

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.

网名女生简单气质 2024-12-20 19:08:25

每个枚举常量都有一个 ordinal 值对应于其在枚举声明中的位置。您可以使用相应枚举常量的序数值为字符串编写比较器。

Every enum constant has an ordinal value corresponding to its position in the enum declaration. You can write a comparator for your strings using the ordinal value of the corresponding enum constant.

一杯敬自由 2024-12-20 19:08:25

values() 方法按照定义的顺序返回。

enum Test{
  A,B,X,D
}

for(Test t: Test.values()){
  System.out.println(t);
}

输出

A
B
X
D

values() method returns in the order in which it is defined.

enum Test{
  A,B,X,D
}

for(Test t: Test.values()){
  System.out.println(t);
}

Output

A
B
X
D
落花浅忆 2024-12-20 19:08:25

我使用以下方法按升序对 List 进行排序,它对我来说效果很好。

Collections.sort(toSortEnumList, new Comparator<theEnum>() {
                @Override
                public int compare(theEnum o1, theEnum o2) {
                    return o1.toString().compareTo(o2.toString());
                }
            });

I used following to sort my List<theEnum> in an ascending order, and it worked fine for me.

Collections.sort(toSortEnumList, new Comparator<theEnum>() {
                @Override
                public int compare(theEnum o1, theEnum o2) {
                    return o1.toString().compareTo(o2.toString());
                }
            });
半衾梦 2024-12-20 19:08:25

如果您想要在 Enum 类中提供不同的排序顺序并且无法修改它,只需将 int 分配给您的枚举字段并比较它:

public class MyComparator implements Comparator<ListE> {

    @Override
    public int compare(ListE o1, ListE o2) {
        return Integer.compare(getAssignedValue(o1), getAssignedValue(o2));
    }

    int getAssignedValue(ListE listE) {
        switch (listE) {
            case LE2:
                return 0;
            case LE1:
                return 1;
            case LE4:
                return 2;
            case LE3:
                return 3;
            default:
                return Integer.MAX_VALUE;
        }
    }

}

然后使用

Collections.sort(myList, new MyComparator());

If you want different sort order then provided in Enum class and you cannot modify it, just assign int to your enum fields and compare it:

public class MyComparator implements Comparator<ListE> {

    @Override
    public int compare(ListE o1, ListE o2) {
        return Integer.compare(getAssignedValue(o1), getAssignedValue(o2));
    }

    int getAssignedValue(ListE listE) {
        switch (listE) {
            case LE2:
                return 0;
            case LE1:
                return 1;
            case LE4:
                return 2;
            case LE3:
                return 3;
            default:
                return Integer.MAX_VALUE;
        }
    }

}

and then use

Collections.sort(myList, new MyComparator());
超可爱的懒熊 2024-12-20 19:08:25

根据规范,乔恩的答案是正确的:

Enum 通过枚举的自然顺序(声明值的顺序)实现 Comparable。

不过,我想留下一个 Java8 示例,以防有人想要将字符串值映射到枚举并按枚举顺序排序。这样,您就可以将字符串映射到枚举,使用默认的可比值进行排序,然后使用 toString 将其映射回来。这会给你留下这样的结果:

enum listE {
    LE1,
    LE4,
    LE2,
    LE3
}

public static void main(String[] args) {
    List<String> originalList = Arrays.asList("LE1", "LE2", "LE3", "LE4");

    System.out.println("Original List: " + originalList);

    List<String> sortedList = originalList.stream()
                                          .map(listE::valueOf)
                                          .sorted(listE::compareTo)
                                          .map(listE::toString)
                                          .collect(Collectors.toList());

    System.out.println("Sorted List: " + sortedList);
}

结果将是:

  • 原始列表:[LE1, LE2, LE3, LE4]
  • 排序列表:[LE1, LE4, LE2, LE3]

Jon's answer is correct per the specification:

Enum implements Comparable via the natural order of the enum (the order in which the values are declared).

However, I wanted to leave a Java8 example in case somebody wants to map string values to an enum and sort by the enum order. With that you can map your strings to the enum, sort using the default comparable, and then map it back using a toString. This leaves you with something like this:

enum listE {
    LE1,
    LE4,
    LE2,
    LE3
}

public static void main(String[] args) {
    List<String> originalList = Arrays.asList("LE1", "LE2", "LE3", "LE4");

    System.out.println("Original List: " + originalList);

    List<String> sortedList = originalList.stream()
                                          .map(listE::valueOf)
                                          .sorted(listE::compareTo)
                                          .map(listE::toString)
                                          .collect(Collectors.toList());

    System.out.println("Sorted List: " + sortedList);
}

The result would be:

  • Original List: [LE1, LE2, LE3, LE4]
  • Sorted List: [LE1, LE4, LE2, LE3]
清醇 2024-12-20 19:08:25

您可能应该查看枚举的 ordinal() 方法,它返回枚举类型在枚举类中出现的位置的整数,因此在您的情况下 LE1 = 0,LE4 = 1 等...

you should probably look at the ordinal() method of the enum, it returns an Integer of the position the enum type appears in the enum class, so in your case LE1 = 0, LE4 = 1, etc...

倥絔 2024-12-20 19:08:25
public class Student implements Comparable<Student>{

    public String studentName;

    public Student(String name,DayInWeek weekDay){
        this.studentName = name;
        this.studentDays = weekDay;
    }

    public enum DayInWeek {
        SATURDAY, SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY
    }
    public DayInWeek studentDays;

    @Override
    public int compareTo(Student s1) {
        if(s1.studentDays.ordinal() < this.studentDays.ordinal())
            return 1;
        else if(s1.studentDays.ordinal() > this.studentDays.ordinal())
            return -1;
        else
            return 1;
    }
}
public class Student implements Comparable<Student>{

    public String studentName;

    public Student(String name,DayInWeek weekDay){
        this.studentName = name;
        this.studentDays = weekDay;
    }

    public enum DayInWeek {
        SATURDAY, SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY
    }
    public DayInWeek studentDays;

    @Override
    public int compareTo(Student s1) {
        if(s1.studentDays.ordinal() < this.studentDays.ordinal())
            return 1;
        else if(s1.studentDays.ordinal() > this.studentDays.ordinal())
            return -1;
        else
            return 1;
    }
}
狼亦尘 2024-12-20 19:08:25

尝试使用:

添加到枚举字段(排序字段),

例如

enum MyEnum{
 private String sorted;
 MyEnum(String sorted){
  this.sorted = sorted;
 }
 String getSorted(){
  return this.sorted;
 }
}

使用 TreeSet

使用 MyEnum.sorted 实现 Comparator 归档

Try to use :

add to enum field(sorted field)

like

enum MyEnum{
 private String sorted;
 MyEnum(String sorted){
  this.sorted = sorted;
 }
 String getSorted(){
  return this.sorted;
 }
}

Use TreeSet

Implement Comparator using MyEnum.sorted filed

电影里的梦 2024-12-20 19:08:25

您可以将以下方法添加到枚举中,以获取已排序的枚举常量数组:

  • 其中 Element 是枚举的名称

  • 枚举的排序位置通过他们的 toString

    public static Element[] getSortedValues(){
        返回 Stream.of(values()).sorted((o1,o2)->
        {
            return o1.toString().compareTo(o2.toString());
        })。
        toArray(元素[]::new);
    }
    

Here is a method you can add to your enumeration to get an array of sorted enumerated constants:

  • Where Element is the name of your Enumeration

  • Where the enumerations are sorted by their toString

    public static Element[] getSortedValues(){
        return Stream.of(values()).sorted((o1,o2)->
        {
            return o1.toString().compareTo(o2.toString());
        }).
        toArray(Element[]::new);
    }
    
我爱人 2024-12-20 19:08:25

如果您想按序数排序,可以使用 valueOf 转换字符串并将它们添加到 EnumSet(按序数排序),

否则您可以根据枚举的属性对值进行排序。 (这可以更稳健,并且不依赖于声明枚举的顺序)使用 valueOf 并编写自定义比较器。

If you wan to sort by ordinal you can use valueOf to convert the string and add these to an EnumSet (which is sorted by ordinal)

Otherwise you can sort the values based on an attribute of the enum. (This can be more robust and not dependent of the order the enums are declared) Use valueOf and write a custom Comparator.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文