Java Sorting based on Enum constants
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());
}
});
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.