Home‎ > ‎Applied Core Java‎ > ‎Collection Framework‎ > ‎

Comparator

Introduction :

A Comparator object is capable of comparing two different objects. It should implement  java.util.Comparator interface.



Comparator interface has one method  Compare(Object o1, Object o2). The return values of the compare() method of Comparator are similar to the compareTo() method of Comparable.
  • if the first element comes before the second element in the ordering, a negative value is returned.
  • If the first element comes after, then a positive value is returned. Otherwise, zero is returned.
  • Similar to Comparable, a zero return value does not signify equality of elements.

Below is the Example of Comparator:

Problem :

Create a program that sort Employees’ list by


1. Employee ID in ascending order

2. Employee ID in descending order

3. Employee Name in ascending order

Solution :

Different kind of sorting will be done by java.util.Comparator interface. There will be a class Employee that keeps employee’s ID and Name. Employees are sorted in 3 three different order so there will be three Comparator classes will be implemented


1.CompareEmployeeByID :Sort by ID in ascending


2.CompareEmployeeByIDDesc : Sort by ID in descending


3.CompareEmployeeByName : Sort by Name in ascending


Program :

Step 1 - Coding


(1)Employee Class

/*
* Keeps Employee information.
*/

public class Employee {

public int id;

public String name;
 

public Employee() {};


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

this.name = name;
}

public int getId() {
return id;
}

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

public String getName() {
return name;
}


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

}



(2)CompareEmployeeByID Class

import java.util.Comparator

/*
* Compare two employees by their ID using Comparator interface implementation.
* Used in Collections.sort() to sort Employees' list in ascending order.

*/

public class CompareEmployeeByID implements Comparator<Employee> {

/*
* Compare Employee IDs and returns
* -1 : If Employee One ID is less than Employee ID Two
* 0 : If both Employee IDs are equal
* 1 : If Employee One ID is greater than Employee ID Two
*/

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

}

(3)CompareEmployeeByIDDesc Class

/*
* Compare two employees by their ID using Comparator interface implementation.
* Used in Collections.sort() to sort Employees' list in descending order.
*/

import java.util.Comparator

public class CompareEmployeeByIDDesc implements
Comparator<Employee> {

/**
* Compare Employee IDs and returns
* 1 : If Employee One ID is less than Employee ID Two
* 0 : If both Employee IDs are equal
* -1 : If Employee One ID is greater than Employee ID Two
*/

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

}


(4)CompareEmployeeByName Class 

import java.util.Comparator;

/*
* Compare two employees by their ID using Comparator interface implementation.
* Used in Collections.sort() to sort Employees' list in ascending order.
*/


public class CompareEmployeeByName implements Comparator<Employee> {

/**

* Compare Employee Names and returns
* -1 : If Employee One Name is less than Employee Name Two
* 0 : If both Employee Names are equal
* 1 : If Employee One Name
* is greater than Employee Name Two
*/
public int compare(Employee emp1, Employee emp2) {


return emp1.getName().compareTo(emp2.getName());
}

}


(5)SortEmployeeListByComparator Class

/*

* A program to compare and sort Employee objects using multiple Comparator implementation.
* A List contains 3 Employee objects and sort it by Employee ID Ascending/ Descending,
* and by Employee Name
*/

import java.io.IOException;
import java.util.*


public class SortEmployeeListByComparator {


public static void main(String[] args) throws IOException {

Employee e1 = new Employee(3, "Ram lal");


Employee e2 = new Employee(1, "Shanti Lal");


Employee e3 = new Employee(2, "Chunni Lal");

ArrayList list = new ArrayList();

list.add(e1);
list.add(e2);
list.add(e3);


// Sort Employee list by Employee ID in ascending order

Collections.sort(list, new CompareEmployeeByID());

Iterator<Employee> itr = list.iterator();
Employee emp = null;


System.out.println("****Employee List By ID ( Ascending )****");


System.out.println("ID\tName");


while (itr.hasNext()) {

emp = itr.next();
System.out.println(emp.getId() + "\t" + emp.getName());

}


// Sort Employees by Employee IDin descending order


Collections.sort(list, new CompareEmployeeByIDDesc());


itr = list.iterator();


System.out.println("****Employee List By ID ( Descending )****");


System.out.println("ID\tName");

while (itr.hasNext()) {

emp = itr.next();
System.out.println(emp.getId() + "\t" + emp.getName());


}


// Sort Employees by Name in ascending order


Collections.sort(list, new CompareEmployeeByName());


itr = list.iterator();


System.out.println("****Employee List BY Name ( Ascending )****");


System.out.println("ID\tName");


while (itr.hasNext()) {

emp = itr.next();
System.out.println(emp.getId() + "\t" + emp.getName());


}

}

}


Step 2 - Deployment

Create a folder 'c:\sunilos'.

Create or copy Employee.java,CompareEmployeeID.java,CompareEmployeeIDDesc.java,CompareEmployeeByName.java,SortEmployeeListByComparator. into 'c:\sunilos' folder.

Open your command prompt and go to 'c:\sunilos'

Compile Employee.java,CompareEmployeeID.java,CompareEmployeeIDDesc.java,CompareEmployeeByName.java,SortEmployeeListByComparator.java with help of

javac *.java java command. Command will create class file in the same folder.

Congratulations!! your Java program is ready to serve.

Step 3 - Testing

Make sure you are on Command Prompt under c:\sunilos directory

Now start your java program from command prompt with help of

java SortEmployeeListByComparator command.

Output :

****Employee List By ID ( Ascending )****

ID Name

1 Shanti Lal
2 Chunni Lal
3 Ram lal

****Employee List By ID ( Descending )****

ID Name

3 Ram lal
2 Chunni Lal
1 Shanti Lal

****Employee List BY Name ( Ascending )****

ID Name

2 Chunni Lal
3 Ram lal
1 Shanti Lal

FAQ

Q.1 What is Comparator and what it is used for?

A : Comparator : A Comparator object is capable of comparing two different objects. instances. This comparator class must implement the java.util.Comparator interface . Comparator interface is used when an extra logic is required to sort the objects. One need to override compare(Object obj1, Object obj2) method.

Q.2 When to use Comparator ?

A : By using Comparator, you could instead make different comparators, one that compares Employee objects by name, and another one that compares them by ID. If you want to sort by name, you use the first Comparator object, and if you want to sort by ID you use the other Comparator object.

Q.3 How many Comparators you can create for a single class say "Employee" ?

A : We can create multiple Comparators for Employee class.  If Employee object need to sort on Name and ID attributes then we will create two Comparators one for Name and second for ID.  That means if Employee class need to sort on 4 attributes then we will create 4 Comparators, one for each attribute.


ċ
CompareEmployeeByID.java
(1k)
Mahima Hardia,
Mar 12, 2011, 5:56 AM
ċ
CompareEmployeeByIDDesc.java
(1k)
Mahima Hardia,
Mar 12, 2011, 5:57 AM
ċ
CompareEmployeeByName.java
(1k)
Mahima Hardia,
Mar 12, 2011, 5:57 AM
ċ
Employee.java
(1k)
Mahima Hardia,
Mar 12, 2011, 5:56 AM
ċ
SortEmployeeListByComparator.java
(2k)
Mahima Hardia,
Mar 12, 2011, 5:57 AM
Comments