Comparator Interface

Comparator Interface

In this tutorial, we are going to discuss Comparator interface in java. By using comparator object we can define our own customized sorting.

The Comparator interface in Java is part of the java.util package and is used to define a custom ordering for objects of a class. It provides a way to compare two objects and determine their relative ordering. This is particularly useful when you want to sort objects in a collection according to a specific criterion that is not based on their natural ordering.

Comparator interface

This interface defines the following 2 methods.

1. public int compare(Object obj1, Object obj2)


 –ve if obj1 has to come before obj2
 +ve if obj1 has to come after obj2
 0 if obj1 and obj2 are equal. 

2. public boolean equals(Object obj)

When ever we are implementing comparator interface compulsory we should provide implementation for compare method. Implementing equals method is optional because it is already available from object class through inheritance.

package com.ashok.collections;

import java.util.*;

 * @author ashok.mariyala
public class MyTreeSet {
   public static void main(String arg[]) {
      TreeSet tset = new TreeSet(new MyComparator());

class MyComparator implements Comparator {
   public int compare(Object obj1, Object obj2) {
      Integer i1 = (Integer) obj1;
      Integer i2 = (Integer) obj2;
      if (i1 < i2)
         return +1;
      else if (i1 > i2)
         return -1;
         return 0;


[85, 68, 45, 12, 0]

That’s all about the Comparator Interface in java. If you have any queries or feedback, please write us email at Enjoy learning, Enjoy Java.!!

Comparator Interface
Scroll to top