Sorting list of objects in natural order
Sort a list of objects in natural order without comparator.
Code Explanation
The java.lang.Comparable interface imposes an ordering on a collection of objects. This ordering is called natural ordering of objects. Collection of objects that implement java.lang.Comparable interface can be sorted automatically using Collections#sort() or Arrays.sort() methods without using java.util.Comparator.
Let us have Cat object and every cat has a name, age and sex. The Cat class implements java.lang.Comparable interface and implements the only method compareTo(). Then in CatNaturalOrdering class we would create a list of cats and then sort this list.
9 public class Cat implements Comparable<Cat> { 10 11 /** 12 * An enum of sex. 13 */ 14 public enum Sex { 15 16 /** 17 * Male. 18 */ 19 MALE, 20 /** 21 * Female. 22 */ 23 FEMALE; 24 } 25 /** 26 * Name. 27 */ 28 private String name; 29 /** 30 * Age. 31 */ 32 private int age; 33 /** 34 * Sex. 35 */ 36 private Sex sex; 37 38 /** 39 * Constructs a new Cat instance. 40 * @param name Name of the cat. 41 * @param age Age of the cat. 42 * @param sex Sex of the cat. 43 */ 44 public Cat(String name, int age, Sex sex) { 45 this.name = name; 46 this.age = age; 47 this.sex = sex; 48 } 107 } 108
Now let us see the definition of compareTo() method which compares two given cats based on their name.
103 @Override 104 public int compareTo(Cat newCat) { 105 return this.name.compareTo(newCat.getName()); 106 } 107
The main() method of CatNaturalOrdering class creates multiple cat objects and adds them to a list. And then Collections#sort() method is called to sort the list in natural order of Cat class.
20 public static void main(String[] args) { 21 Cat cat1 = new Cat("Magic", 5, Sex.MALE); 22 Cat cat2 = new Cat("Ajax", 8, Sex.MALE); 23 Cat cat3 = new Cat("Alpha", 6, Sex.FEMALE); 24 Cat cat4 = new Cat("Gigolo", 1, Sex.MALE); 25 Cat cat5 = new Cat("Jessica", 2, Sex.FEMALE); 26 List<Cat> cats = new ArrayList<Cat>(); 27 cats.add(cat1); 28 cats.add(cat2); 29 cats.add(cat3); 30 cats.add(cat4); 31 cats.add(cat5); 32 CatNaturalOrdering sortTest = new CatNaturalOrdering(); 33 sortTest.printCats("############# List Of Cats #############", cats); 34 Collections.sort(cats); 35 sortTest.printCats( 36 "############# Natural Ordering of Cats #############", cats); 37 } 38
Input and Output
Following Cats were given as input:
"Magic", 5, MALE "Ajax", 8, MALE "Alpha", 6, FEMALE "Gigolo", 1, MALE "Jessica", 2, FEMALE
The output of the program is:
############# List Of Cats ############# name: Magic age: 5 sex: MALE name: Ajax age: 8 sex: MALE name: Alpha age: 6 sex: FEMALE name: Gigolo age: 1 sex: MALE name: Jessica age: 2 sex: FEMALE ############# Natural Ordering of Cats ############# name: Ajax age: 8 sex: MALE name: Alpha age: 6 sex: FEMALE name: Gigolo age: 1 sex: MALE name: Jessica age: 2 sex: FEMALE name: Magic age: 5 sex: MALE