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"]
.
Here is one option. You can have the Enum implement the Comparator interface for type Employee then delegate the Comparator to each element by having a constructor that provides a Comparator.
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.
According to the documentation for Enumset, the iterator should return the Enum constants in the order in which they were declared. The iterator returned by the iterator method traverses the elements in their natural order (the order in which the enum constants are declared).
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With