Java Sorting based on Enum constants

2019-01-06 19:25发布

问题:

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"].

回答1:

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.



回答2:

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


回答3:

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());
                }
            });


回答4:

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



回答5:

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.



回答6:

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;
    }
}


回答7:

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



回答8:

If you want different sort order then provided in Enum class and you cannot modified it just assigned 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());


回答9:

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.