Comparator interface in Java

The Comparator  interface in Java is widely using in sorting objects in  data structures like TreeSet or TreeMap.The Comparator interface is having one abstract method compare(Object arg1,Object arg2) .The compare() method returns an integer value.The concept will become clear once we do an example.

If we are using the Comparator instance for sorting a number of objects in TreeSet or TreeMap , then  we need to pass the Comparator instance while initializing the data structure.(unlike from the case of Comparable ).

In this example we are planning to put few Student objects in a TreeSet. We need those objects in ascending order of attribute ‘id’. Now see the first.

public class Student {
private int id;
private String name;
public Student(int number, String name) { = number; = name;
public int getId() {
return id;
public void setId(int id) { = id;
public String getName() {
return name;
public void setName(String name) { = name;
public String toString() {
return "Id = " + getId() + " ; Name = " + getName();

Now we need a Comparator unit . The compare() method should do the comparison to arrange the TreeSet elements in ascending order.

import java.util.Comparator;
public class StudentComparator implements Comparator {
public int compare(Student student1, Student student2) {
return student1.getId() - student2.getId();

Now let us see the It creates a TreeSet object with the StudentComparator instance as argument.

import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class ComparatorSample {
private Set set = null;
Comparator studentComparator = null;
public ComparatorSample() {
studentComparator = new StudentComparator();
set = new TreeSet(studentComparator);
public void addItems() {
Student student1 = new Student(2, "Bijoy");
Student student2 = new Student(1, "Karthik");
Student student3 = new Student(3, "Dexter");
Student student4 = new Student(4, "Sasi");
public void displayItems() {
Iterator itr = set.iterator();
System.out.println("In ascending order");
while (itr.hasNext()) {
public static void main(String[] args) {
ComparatorSample sample = new ComparatorSample();

The addItems() method is adding few Student objects to the TreeSet. The displayItems() method is displaying the contents. The output is in a sorted order. The compare() method of makes the TreeSet elements in the ascending order of attribute ‘id’.


In ascending order

Id = 1 ; Name = Karthik

Id = 2 ; Name = Bijoy

Id = 3 ; Name = Dexter

Id = 4 ; Name = Sasi

If we reverse the logic in compare() method(change it to  return student2.getId() – student1.getId()) ,then  the TreeSet will be in descending order

See Related Topics:

Collections in Java

Threading in Java

Comparable vs Comparator in Java

Comparable in Java