Java Sorting based on Enum constants

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


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

Solution 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

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

Solution 4:

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.