«Back to Home

Core Java

Topics

Comparator Interface In Java

Comparator Interface
 
In Java, comparator interface orders the objects of user-defined class. This interface is found in java.util package and it holds the two methods compare (Object obj1, Object obj2) and equals (Object element). It provides multiple sorting sequence i.e. we can sort the elements on the basis of any data member.
 
Method

public int compare(Object obj1,Object obj2)

This method is used to compare the first object with the second object.
 
Let’s see an example, given below.
 
Code
  1. public class Employee {  
  2.     int empId;  
  3.     String empName;  
  4.     int empAge;  
  5.     Employee(int empId, String empName, int empAge) {  
  6.         this.empId = empId;  
  7.         this.empName = empName;  
  8.         this.empAge = empAge;  
  9.     }  
  10. }  
  1. import java.util.*;  
  2. public class SortName implements Comparator < Employee > {  
  3.     public int compare(Employee e1, Employee e2) {  
  4.         return e1.empName.compareTo(e2.empName);  
  5.     }  
  6. }  
  1. import java.util.*;  
  2. public class SortAge implements Comparator < Employee > {  
  3.     public int compare(Employee e1, Employee e2) {  
  4.         if (e1.empAge == e2.empAge) {  
  5.             return 0;  
  6.         } else if (e1.empAge > e2.empAge) {  
  7.             return 1;  
  8.         } else {  
  9.             return -1;  
  10.         }  
  11.     }  
  12. }  
  1. import java.util.*;  
  2. import java.io.*;  
  3. public class CollectionSort {  
  4.     public static void main(String args[]) {  
  5.         ArrayList < Employee > a = new ArrayList < Employee > ();  
  6.         a.add(new Employee(11"Harry"29));  
  7.         a.add(new Employee(16"Jack"37));  
  8.         a.add(new Employee(15"Jones"31));  
  9.         System.out.println("Sorting with Name:");  
  10.         Collections.sort(a, new SortName());  
  11.         for (Employee em: a) {  
  12.             System.out.println(em.empId + " " + em.empName + " " + em.empAge);  
  13.         }  
  14.         System.out.println("Sorting with age:");  
  15.         Collections.sort(a, new SortAge());  
  16.         for (Employee em: a) {  
  17.             System.out.println(em.empId + " " + em.empName + " " + em.empAge);  
  18.         }  
  19.     }  
  20. }  
8

9

10

11

Output

12

In the example, mentioned above, the classes provide the comparison logic, based on the name and age. In such case, we are using the compareTo() method of String class, which internally provides the comparison logic and then we are printing the objects values by sorting on the basis of the name and the age.
 
Summary

Thus, we learnt that Java comparator interface orders the objects of user-defined class. This interface is found in java.util package. It holds the two methods compare (Object obj1, Object obj2), equals (Object element) and also learnt how to create it in Java.