Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – Comparator

Note

Before learning Comparator interface please try to understand Comparable interface explained by this website.

Declaration of Comparator interface

interface Comparator<T>

Comparator interface has two methods as explained below:

Java Programming Language Comparator Interface

It is optional to implement equals() method when we implement Comparator interface because it is already inherited through Object class.
The equals() method is implemented only if we want to change its default functioning.

Comparator interface is mainly used when we want sorting order of elements according to our requirement but not default (natural sorting order).

For example, TreeSet & TreeMap uses natural sorting order. That is in ascending order as shown below.

Non Comparator Demo

 class NonComparatorDemo 
 { 
     public static void main(String agrs[])
     {
         TreeSet<Integer> t = new TreeSet<Integer>();
         t.add(10);
         t.add(20);
         t.add(30);
         t.add(40);
         t.add(50);
         System.out.println(t);
     }
 }

Output

[10, 20, 30, 40, 50]

But what if we want customized sorting order (user demand)?
For example, suppose we want all the Integer elements to be sorted in reverse order.
It is not possible with above program because all the Integer uses compareTo() method of the Comparable interface by default to compare all Integer objects. Therefore all the Integer objects are sorted in natural ascending order.
If we want all Integer elements in above program to be sorted in reverse order or any other order, we must implement Comparator interface, as shown below:

 import java.util.Comparator;
 import java.util.TreeSet;

 class CustomizedComparator implements Comparator<Integer>
 {
     public int compare(Integer ob1, Integer ob2)
     {
        return ob2.compareTo(ob1);
     }
 }

 class ComparatorDemo 
 {
     public static void main(String agrs[])
     {
         TreeSet<Integer> t = new TreeSet<Integer>(new CustomizedComparator());
         t.add(10);
         t.add(20);
         t.add(30);
         t.add(40);
         t.add(50);
         System.out.println(t);
     }
 }

Output

[50, 40, 30, 20, 10]

 

Leave a reply