Friday, 9 September 2022

Comparable and Comparator

Java supports sorting on collection in two ways - through Comparable and Comparator(both are functional interfaces with one single abstract method).

Comparable:

To sort collection based on Comparable:

  • Elements of the collection must implement Comparable interface and implement it's method "int compareTo(Object o1)".
  • Then sorting can be done using Collections.sort(List)

Cons:

  • Can't support multiple types of sorting, as one compareTo method can have only one implementation.
  • May not have access to the element class, in which case, subclassing the element and implementing compareTo would be the only option.

Code:

public class Dog implements Comparable<Dog>{
      String name;
      String breed;

      public Dog(String name,String breed){
            this.name = name;
            this.breed = breed;
      }
        @Override
public int compareTo(Dog o) {
return name.compareTo(o.name);
}
}
...

List<Dog> dogList = new ArrayList<Dog>();
Collections.sort(dogList);
...


Comparator:

To sort collection based on Comparator:

  • A class/anonymous class implements Comparator interface and implements it's method "int compare(Object o1, Object o2). 
  • Then sorting can be done by passing the object of the above implmented Comparator - using Collection.sort(List, Comparator).

Pros:

  • Can support multiple sorting implementations.
  • Don't need to have access to elements of the collection.

Code:

public class DogBreedComparator implements Comparator<Dog> {
@Override
public int compare(Dog o1, Dog o2) {
return o1.breed.compareTo(o2.breed);
}
}
..

Collections.sort(dogList, new DogBreedComparator());
..
Lambda expression:
Collections.sort(dogList, (o1,o2)->o1.breed.compareTo(o2.breed));
..

Both compareTo and compare methods return integer - 
1  : if passed in object is greater than current object
-1: if passed in object is lesser than current object
0: if both are equal

~