Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a List<Enum, Collection> by order of an enum?

Enum:

 public enum ComponentType {
    INSTRUCTION, ACTION, SERVICE, DOMAIN, INTEGRATION,  OTHER, CONTEXT;
 }

Class A :

 public class A
 {
    String name;
    ComponentType c;
    public A(String name, ComponentType c)
    {
      this.name = name;
      this.c = c;
    }

 }   

Code:

 List<A> l = new ArrayList<A>();
 l.add(new A("ZY", ACTION));  
 l.add(new A("ZY0", INSTRUCTION));  
 l.add(new A("ZY1", DOMAIN));  
 l.add(new A("ZY2", SERVICE));  
 l.add(new A("ZY3", INSTRUCTION));  
 l.add(new A("ZY4", ACTION));  

How to sort list according to enum order?

like image 966
Shashi Avatar asked Nov 19 '12 07:11

Shashi


1 Answers

You should simply delegate to the enum compareTo method which is already provided and reflects the declaration order (based on the ordinal value):

Collections.sort(list, (a1, a2) -> a1.getType().compareTo(a2.getType()));        

Or, if you think that the component type provides the "natural order" for your elements, you can make the A class itself implement Comparable and also delegate the compareTo method to the ComponentType one.

like image 133
Costi Ciudatu Avatar answered Nov 09 '22 20:11

Costi Ciudatu