Top java puzzles

Comparator interface in java

Comparator interface

 
The Comparator interface is used to define the sort order of a collection of objects, without requiring them to implement this interface.
 

We can also sort a collection of objects in natural order, if the corresponding class implements Comparable interface.

Read more about Comparable interface.
 
 
Comparator interface is useful in scenarios where :
 
– We need to sort instances of a class that you can’t modify and that doesn’t implement Comparable.
 
– We want to sort the objects using sorting logic other than the natural order.
 
 

compare() method in Comparator

 
Comparator interface declares two methods:
 
 
boolean equals(Object obj);
 

int compare(T o1, T o2);
 
The compare() method is used for comparing objects. It takes two Object arguments and returns an integer value.
 
compare() method returns a negative integer, zero, or a positive integer if object o1 is less than, equal to, or greater than object o2.
 
 

Implementing Comparator

 
So, let’s see how to use Comparator interface for sorting instances of an Employee class.
 
Here is the code for the simple Employee class :
 

package com.topjavatutorial;

public class Employee {

  int id;

  String name;

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

}


 
Now, lets say we want to sort the employees in descending order of their id number instead of their name.
 
We can implement a simple Comparator as follows :
 
package com.topjavatutorial;

import java.util.Comparator;

public class EmployeeComparator implements Comparator<Employee>{

  @Override
  public int compare(Employee emp1, Employee emp2) {
    
    return emp2.id - emp1.id;
  }

}


 
Now, we can use the EmployeeComparator to sort employees as follows :
 
package com.topjavatutorial;

import java.util.TreeSet;

public class TreeSetDemo{

  public static void main(String[] args) {

    TreeSet<Employee> empTreeSet = new TreeSet<Employee>(new EmployeeComparator());
    
    Employee emp1 = new Employee(20, "Clark");
    Employee emp2 = new Employee(24, "Bernie");
    Employee emp3 = new Employee(3, "Alex");
    
    empTreeSet.add(emp1);
    empTreeSet.add(emp2);
    empTreeSet.add(emp3);
    
    
    for(Employee emp : empTreeSet)
            System.out.println(emp.id + " " + emp.name);
    

  }

}


 
Running this example produces employee details in descending order of their id numbers :
 
24 Bernie
20 Clark
3 Alex
 
 
Here, the Employee class no longer needs to implement the Comparable interface. The sorting logic is outside Employee class in a separate class.
 
But, what will happen if the Employee class still had the logic to implement Comparable interface along with the EmployeeComparator class ?
 
 

Using both Comparable and Comparator

 
If we have a class implementing Comparable interface and we use a Comparator as well, then it will be sorted as per the order specified in Comparator.
 
To verify this, modify Employee class to implement Comparable interface as follows :
 

package com.topjavatutorial;

public class Employee implements Comparable<Employee>{

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

  @Override
  public int compareTo(Employee emp) {
    return this.name.compareTo(emp.name);
  }
  
}


 
Here, the compareTo() method implementation sorts employees based on the natural order of names. Since, name is of string type, employees will be sorted in ascending order of names.
 
We leave the EmployeeComparator logic as is where it sorts employees in descending order of their ids.
 
package com.topjavatutorial;

import java.util.Comparator;

public class EmployeeComparator implements Comparator<Employee>{

  @Override
  public int compare(Employee emp1, Employee emp2) {
    
    return emp2.id - emp1.id;
  }

}


 
Now, if we run the TreeSetDemo class, the output will be :
 
24 Bernie
20 Clark
3 Alex
 
Comparator takes precedence over Comparable, so Employee instances are sorted using Comparator.
 
 

Comparable vs. Comparator

 
Comparable interface is used when sorting order can be added inside the same class and the objects can be sorted according to natural order of fields.
 
Comparable interface is used when sorting information isn’t available inside the object itself or a custom sorting logic needs to be implemented.
 
 
 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

One comment

  1. […] Read more about Comparator interface […]

Leave a Reply.. code can be added in <code> </code> tags

%d bloggers like this: