Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 550
Sukhhhh Avatar asked Nov 04 '11 09:11

Sukhhhh


People also ask

How can I sort employee objects using enum constants?

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.

How do you sort a list by enum?

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.

Are enums ordered Java?

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

Are constants allowed in enum?

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.


2 Answers

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.

like image 93
Jon Skeet Avatar answered Sep 28 '22 11:09

Jon Skeet


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 
like image 36
jmj Avatar answered Sep 28 '22 10:09

jmj