Monday, March 28, 2022

Comparable vs Comparator in Java

Comparable Interface

is used to sort the objects of a user defined class. It contains only one method: compareTo()

public interface Comparable<T>{
  int compareTo(T o);
}

We can implement the logic of the sorting into the compareTo() method (an example is given below). compareTo() method must returns an integer based on the following rules:

  • 0 is returned when current object is equal to the argument object
  • -1 is returned when current object is smaller than the argument object
  • 1 is returned when current object is greater than the argument object
class Employee implements Comparable<Employee> {
    private String empCode;
    private String name;
    private int age;
    //not including getters, setters, constructor etc
    @Override
    public String toString() {
        return "Emp{" + name + "," + age + "," + empCode + "}";
    }

    @Override
    public int compareTo(Employee o) {
        int result = this.name.compareTo(o.getName());
        if (result != 0) return result;
        return this.getAge() - o.getAge();
    }
}

public class Main {
    public static void main(String[] args) {
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee("402", "anu", 35));
        employees.add(new Employee("399", "binoy", 32));
        employees.add(new Employee("400", "anu", 31));
        //printing before sort
        System.out.println(employees); //outputs [Emp{anu,35,402}, Emp{binoy,32,399}, Emp{anu,31,400}]
        Collections.sort(employees);
        //printing after sort
        System.out.println(employees); //outputs [Emp{anu,31,400}, Emp{anu,35,402}, Emp{binoy,32,399}]
    }
}

Comparator Interface

Comparator is also an interface which is used to sort the objects of a user defined class. It contains compare() method. Using Comparable interface we can implement only one sorting logic. What if we need to implement sorting logic based on other data members also. At that time Comparator becomes handy. In the above example, of Comparable interface, if we need to sort the employees based on their employee code (empCode). Then we can implement it by modifying the main code as shown below:

//sorting based on empCode
Comparator<Employee> comparatorByEmpCode = (e1, e2) -> e1.getEmpCode().compareTo(e2.getEmpCode());
Collections.sort(employees, comparatorByEmpCode);
System.out.println(employees); //outputs [Emp{binoy,32,399}, Emp{anu,31,400}, Emp{anu,35,402}]

We can also combine the comparators to get a particular sorting sequence. For example say we need to display the employee based on their name. But when name is same then the employee with smallest age will be listed first. Find the example below:-

Comparator<Employee> comparatorByName = Comparator.comparing(Employee::getName);
Comparator<Employee> comparatorByAge = Comparator.comparing(Employee::getAge);
Comparator<Employee> comparatorCombined = comparatorByName.thenComparing(comparatorByAge);
Collections.sort(employees, comparatorCombined);
System.out.println(employees);

Comparable vs Comparator

As seen above both are used for sorting purposes. The differences between them are as follows:

  • Comparable provides only a single sorting logic whereas with the help of Comparator we can implement multiple sorting logic.
  • Comparable has compareTo() method with a single parameter. Comparator has compare() method with two parameters
  • Comparable is present in java.lang package while Comparator is present in java.util package
  • To implement sorting using Comparable we need to modify the class, but in the case of Comparator we do not need to modify the class.
  • If a class implements Comparable interface then collection of that object can be sorted using Collections.sort() or Arrays.sort() method. They will be sorted based on the logic defined by compareTo() method.

No comments:

Post a Comment