Comparable vs Comparator in Java

Java Programming Java8Object Oriented Programming

Comparable

Comparable interface is used when we want to compare objects using one of their property. It is considered a natural sorting of objects. Consider a list of employees and we want them to be sorted by name as a default sorting order. The comparable interface has compareTo() method which the target class has to implement.

class Employee implements Comparable {
   String name;
   public int compareTo(Employee o) {        
      return name.compareTo(o.name);
   }
}

Now a collection of the above objects can be sorted by name using Collections.sort() method.

Collections.sort(employees);

Comparator

Comparator interface provides a compare() method to compare two objects of the same class. Here it provides the flexibility as we can create n number of comparators for each property of an object which we want to compare. Consider the following examples:

class IdComparator implements Comparator<Employee> {
   public int compare(Employee o1, Employee o2) {
      if (o1.getId() < o2.getId()) {
         return -1;        
      }else if (o1.getId() > o2.getId()) {          
         return 1;
      } else {
         return 0;        
      }
   }
}

class AgeComparator implements Comparator<Employee> {
   public int compare(Employee o1, Employee o2) {
      if (o1.getAge() < o2.getAge()) {
         return -1;        
      }else if (o1.getAge() > o2.getAge()) {          
         return 1;
      } else {
         return 0;        
      }    
   }
}

Example

In this example, we are showcasing the usage of comparable as well as comparator interfaces to sort a list of employees based on their names, id, and age respectively.

Live Demo

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
 
public class Tester {
   public static void main(String[] args) {
      List<Employee> employees = new ArrayList<>();

      employees.add(new Employee(1, 20, "A"));
      employees.add(new Employee(4, 26, "D"));
      employees.add(new Employee(2, 23, "C"));
      employees.add(new Employee(3, 25, "B"));
      employees.add(new Employee(5, 24, "E"));

      //Unordered list
      System.out.println("Unsorted List");
      System.out.println(employees);

      //Sorted by natural order on employee name,
      //as provide by compareTo method
      Collections.sort(employees);

      //Ordered list
      System.out.println("Sorted List on Name");
      System.out.println(employees);

      //Sorted by id of employees,
      //as provide by IdComparator
      Collections.sort(employees, new IdComparator());

      //Ordered list
      System.out.println("Sorted List on Id");
      System.out.println(employees);

      //Sorted by age of employees,
      //as provide by AgeComparator
      Collections.sort(employees, new AgeComparator());

      //Ordered list
      System.out.println("Sorted List on Age");
      System.out.println(employees);
   }
}

class Employee implements Comparable<Employee> {
   private int id;
   private int age;
   private String name;

   public Employee(int id, int age, String name) {
      this.id = id;
      this.age = age;
      this.name = name;
   }

   public int compareTo(Employee o) {        
      return name.compareTo(o.name);
   }

   public String toString() {
      return "\n[Id: " + id + ", age: " + age + ", name: " + name +" ]";
   }

   public int getId() {
      return id;
   }

   public void setId(int id) {
      this.id = id;
   }

   public int getAge() {
      return age;
   }

   public void setAge(int age) {
      this.age = age;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }
}

class IdComparator implements Comparator<Employee> {
   public int compare(Employee o1, Employee o2) {
      if (o1.getId() < o2.getId()) {
         return -1;        
      }else if (o1.getId() > o2.getId()) {          
         return 1;
      } else {
         return 0;        
      }
   }
}

class AgeComparator implements Comparator<Employee> {
   public int compare(Employee o1, Employee o2) {
      if (o1.getAge() < o2.getAge()) {
         return -1;        
      }else if (o1.getAge() > o2.getAge()) {          
         return 1;
      } else {
         return 0;        
      }    
   }
}

Output

Unsorted List
[
[Id: 1, age: 20, name: A ],  
[Id: 4, age: 26, name: D ],  
[Id: 2, age: 23, name: C ],  
[Id: 3, age: 25, name: B ],  
[Id: 5, age: 24, name: E ]]
Sorted List on Name
[
[Id: 1, age: 20, name: A ],  
[Id: 3, age: 25, name: B ],  
[Id: 2, age: 23, name: C ],  
[Id: 4, age: 26, name: D ],  
[Id: 5, age: 24, name: E ]]
Sorted List on Id
[
[Id: 1, age: 20, name: A ],  
[Id: 2, age: 23, name: C ],  
[Id: 3, age: 25, name: B ],  
[Id: 4, age: 26, name: D ],  
[Id: 5, age: 24, name: E ]]
Sorted List on Age
[
[Id: 1, age: 20, name: A ],  
[Id: 2, age: 23, name: C ],  
[Id: 5, age: 24, name: E ],  
[Id: 3, age: 25, name: B ],  
[Id: 4, age: 26, name: D ]]
raja
Updated on 18-Jun-2020 15:00:17

Advertisements