Comparator Interface


  • Comparator interface is used to define our own sorting(customized sorting).
  • It is present in java.util package.
  • It defines two methods, such as compare() and equals().


The general form is:
public int compare(Object ob1, Object ob2)

here the compare() method having 3 cases, like:
Returns -ve if ob1 have to come before ob2.
Returns +ve, if ob1 have to come after ob2.
Returns 0, if ob1 and ob2 are equal.

public boolean equals()



  • Whenever we are implementing Comparator interface, compulsory we should provide implementation for compare() method.
  • Implementing equals() method is optional, because it is already available in every java class from Object class through inheritance.

package java8s;
import java.util.*;
class ComparatorDemo {
      public static void main(String[] args) {
            TreeSet t=new TreeSet(new MyComparator());

class MyComparator implements Comparator
      public int compare(Object ob1, Object ob2)
            Integer i1=(Integer)ob1;
            Integer i2=(Integer)ob2;
                  return +1;
                        return -1;
                        return 0;


[90, 50, 20, 0]

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Data Science with Python Training | Projects

SILAN Technology, BBSR
Call to: 0674-2361252