Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Comparator in Java | Use, Example

Last Updated on January 13, 2021 by Scientech Easy

Comparator in Java is an interface whose task is to compare objects of a user-defined class when the class does not implement the Comparable interface.

In other words, Java Comparator is used when:

  • Objects to be ordered do not have a natural ordering defined by Comparable interface.
  • You want to order elements something different way other than their natural order.

In both cases, we can specify a Comparator object when you construct the set or map.

Comparator interface was introduced in Java 1.2 version. It is present in java.util.Comparator package.

Comparator interface in Java

Comparator Interface declaration


Comparator is a generic interface that can be declared in general form like this:

Interface Comparator

Here, the parameter T represents the type of objects (or elements) that will be compared.

Methods of Java Comparator Interface


Comparator interface provides two methods that are as follows:

1. int compare(Object obj1, Object obj2): It compares the first object obj1 with the second object obj2. It returns zero if objects are equal (i.e. obj1 == obj2).

It returns a positive value if obj1 is greater than obj2 (i.e. obj1 > obj2). Otherwise, a negative value is returned.

Let’s take an example to understand better. Comparator looks like this:

public interface Comparator
{
   int compare(Country a, Country b);
}

The call to com.compare(a, b); will return a negative value if a come before b, 0 if a and b are equal, and a positive value. Here, com is an object of a class that implements Comparator.

The compare() method can throw an exception named ClassCastException if types of objects are not compatible for comparison.

By overriding the compare( ) method, we can change the way that objects are ordered. For example, to sort elements in reverse order, we can create a comparator object that reverses the outcome of a comparison.

2. boolean equals(Object obj): The equals() method defined in the Comparator interface is overridden of the equals() method of the Object class. It is used to test whether an object equals invoking comparator.

Here, the parameter obj is the object to be tested for equality. If object obj and the invoking object both are Comparator objects and use the same ordering. the equals() method returns true. Otherwise, it returns false.

Overriding equals( ) is not always necessary. When it is not necessary, there is no requirement to override Object’s implementation.

The complete declaration of the Comparator class that is defined in java.util package is as follows:

public interface Comparator {
 // An abstract method declared in the interface
      int compare(Object obj1, Object obj2);
// Re-declaration of the equals() method of the Object class
      boolean equals(Object obj);
}

Example Programs based on Sorting using Comparator in Java


Let’s take an example program where we will perform sorting of integer elements in ascending order using comparator. Look at the following source code to understand the power of custom comparator.

Program source code 1:

import java.util.Comparator;
// To sort elements into ascending order.
public class Ascend implements Comparator
{
@Override
public int compare(Integer i1, Integer i2) {      
   return i1.compareTo(i2);
  }
  // No need to override equals method.
}
import java.util.TreeSet;
public class CompTest {
public static void main(String[] args) 
{
// Create an object of Ascend class.	
   Ascend as = new Ascend();

// Create a tree set and pass the reference variable of Ascend class as a parameter.
  TreeSet ts = new TreeSet(as);	
  
// Adds elements into treeset.   
  ts.add(25);
  ts.add(15);
  ts.add(30);
  ts.add(10);
  ts.add(40);
  ts.add(05);
  
// Display the elements in ascending order. 
  System.out.println("Sorted in Ascending order");
  for(Integer element : ts)  
    System.out.print(element + " ");
    System.out.println();  
   }
}
Output:
      Sorted in Ascending order
      5 10 15 25 30 40

Explanation: Look closely at the Ascend class, which implements Comparator and overrides compare( ) method. As explained earlier, overriding equals( ) method is needed here. Inside compare( ) method, the compareTo( ) compares the two integers.

How to Sort Elements in Descending Order using Comparator in Java


Let’s write a program to sort elements in descending order using Comparator in Java. Look at the source code.

Program source code 2:

import java.util.Comparator;
// To sort elements into descending order.
public class Descend implements Comparator{
@Override // Implement compare() method to reverse for the integer comparison.
public int compare(Integer i1, Integer i2)
{
// For reverse comparison. 
   return i2.compareTo(i1);	
 }
}
import java.util.TreeSet;
public class CompTest {
public static void main(String[] args) 
{
// Create an object of Descend class.	
  Descend ds = new Descend();

// Create a tree set and pass the reference variable of Descend class as a parameter.
  TreeSet ts = new TreeSet(ds);	
  
// Adds elements into tree set.   
  ts.add(25);
  ts.add(15);
  ts.add(30);
  ts.add(10);
  ts.add(40);
  ts.add(05);
  
// Display the elements in ascending order. 
  System.out.println("Sorted in Descending order");
  for(Integer element : ts)  
    System.out.print(element + " ");
    System.out.println();  
   }
}
Output:
      Sorted in Descending order
      40 30 25 15 10 5

Let’s take one more example program similar to the above program where we will perform reverse string comparison.

Program source code 3:

import java.util.Comparator;
// To sort elements into descending order.
public class RevStrComp implements Comparator{
@Override // Implements compare() method for reverse string comparison.
public int compare(String str1, String str2)
{
// For reverse comparison. 
   return str2.compareTo(str1);	
 }
}
import java.util.TreeSet;
public class CompTest {
public static void main(String[] args) 
{
// Create an object of RevStrComp class.	
  RevStrComp rsc = new RevStrComp();

// Create a tree set and pass reference variable of RevStrComp class as parameter.
  TreeSet ts = new TreeSet(rsc);	
  
// Adds elements into tree set.   
  ts.add("Cat");
  ts.add("Elephant");
  ts.add("Lion");
  ts.add("Dog");
  ts.add("Tiger");
  ts.add("Horse");
  
// Display the elements in ascending order. 
  System.out.println("Sorted in reverse order");
  for(String element : ts)  
    System.out.print(element + " ");
    System.out.println();  
  }
}
Output:
      Sorted in reverse order
      Tiger Lion Horse Elephant Dog Cat

Sorting Array using Comparator


Let’s take an example program where we will sort an array with group of integer elements (objects) using Comparator in java.

Here, we will accept array elements from the keyboard and sort them in ascending and descending order. Look at the following source code.

Program source code 4:

import java.util.Comparator;
// To sort elements into ascending order.
public class Ascend implements Comparator
{
@Override
public int compare(Integer i1, Integer i2) {      
	return i1.compareTo(i2);
 }
}
import java.util.Comparator;
// To sort elements into descending order.
public class Descend implements Comparator{
@Override 
public int compare(Integer i1, Integer i2)
{
// For reverse comparison. 
   return i2.compareTo(i1);	
 }
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class ArraysCompTest {
public static void main(String[] args) throws NumberFormatException, IOException 
{
// Create an object of InputStreamReader class to accept array elements from the keyboard.
  InputStreamReader isr = new InputStreamReader(System.in);	
	
// Create an object of BufferedReader and pass the reference variable to its constructor.
   BufferedReader br = new BufferedReader(isr);

 System.out.println("How many elements do you want to enter?");   
 int size = Integer.parseInt(br.readLine());
 
// Create an array to store Integer type elements or objects.
  Integer arr[] = new Integer[size];
  
// Now convert int values into Integer objects and then pass to array to store them. 
   for(int i = 0; i 
Output:
      How many elements do you want to enter?
      5
      Enter your number:
      12
      Enter your number:
      10
      Enter your number:
      15
      Enter your number:
      20
      Enter your number:
      05

      Sorted in Ascending order: 
      5	
      10	
      12	
      15	
      20	

      Sorted in Descending order: 
      20	
      15	
      12	
      10	
      5

When to use Comparable and Comparator interfaces in Java


Both Comparable and Comparator interfaces are used to sort the collection or array of elements (objects). But there are the following differences in use. They are as follows:

Use of Comparable interface in Java

1. Comparable interface is used for the natural sorting of objects. For example, if we want to sort Employee class by employeeId is natural soring.

2. Comparable is used to sort collection of elements based on only a single element (or logic) like name.

3. Comparable interface is used when we want to compare itself with another object.

Use of Comparator interface in Java

1. Comparator interface is used when we want to perform custom sorting on the collection of elements. It gives exact control over the ordering. For example, if we want to sort Employee class by name and age, it will be custom sorting.

2. Comparator is used to sort collection of elements based on multiple elements (or logics )like name, age, class, etc.

3. Comparator interface is used when we want to compare two different objects.

Hope that this tutorial has covered the important points related to Comparator interface in Java with example programs. I hope that you will have understood and practiced example programs.
Thanks for reading!!!

The post Comparator in Java | Use, Example appeared first on Scientech Easy.



This post first appeared on Scientech Easy, please read the originial post: here

Share the post

Comparator in Java | Use, Example

×

Subscribe to Scientech Easy

Get updates delivered right to your inbox!

Thank you for your subscription

×