Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is the Java Comparator Interface?
3.
Methods of Java Comparator Interface
3.1.
compare() Method
3.1.1.
Syntax 
3.1.2.
Return Value 
3.2.
equals() Method
3.2.1.
Syntax
3.2.2.
Return Value 
4.
Java Comparator Example
4.1.
Java
5.
Java Comparator Interface to Sort an Object
5.1.
Java
6.
Java Comparable Vs Java Comparator
7.
Frequently Asked Questions
7.1.
What is a Comparable interface in Java?
7.2.
What is the Comparator functional interface?
7.3.
Why use a Comparable interface in Java?
7.4.
When to use Comparator?
8.
Conclusion
Last Updated: May 17, 2024
Medium

Comparator Interface in Java with Examples

Author Shiva
0 upvote
Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

Java Comparator is a part of the Java Collection Framework. The Java Collection framework is a large collection of classes and interfaces that provide a versatile architecture for storing, organising, and manipulating groupings of objects. It provides a diverse set of data structures and algorithms for performing actions on collections of items, such as searching, sorting, insertion, manipulation, and deletion.

java comparator

In this article, we'll take a look at Java Comparator and its methods. We will also solidify our understanding with an example.

What is the Java Comparator Interface?

The Comparator interface in the Java Collections Framework provides a way to order objects of user-defined classes based on specific criteria. It allows for custom comparison logic, enabling sorting operations on objects that may belong to different classes.

The following are some use cases of the Java Comparator Interface:-

  • Customized Sorting: The primary advantage of the Comparator interface is that it allows you to define custom sorting orders for objects that may not have a natural ordering.
     
  • Separate Sorting Logic: With the Comparator interface, you can separate the sorting logic from the class definition itself. This makes your code cleaner and more maintainable.
     
  • Multiple Sorting Orders: You can define multiple Comparator implementations for the same class, each representing a different sorting order. This allows you to sort the same set of objects in various ways without modifying the original class.
     

Now, let us take a look at the methods of the Java comparator interface.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Methods of Java Comparator Interface

The Comparator interface contains two methods:

  • Compare Method
     
  • Equals Method

compare() Method

This method compares two objects, obj1, and obj2, and returns an integer value to indicate their relative order. 

Syntax 

public int compare(Object obj1, Object obj2)

 

Return Value 

The return value follows the following convention:

  • If obj1 should be placed before obj2, a negative value is returned.
     
  • If obj1 should be placed after obj2, a positive value is returned.
     
  • If obj1 and obj2 are considered equal in terms of ordering, zero is returned.

equals() Method

This method checks whether the invoking Comparator is equal to the specified element. It returns true if the element is also a Comparator object and both Comparators impose the same ordering.

By implementing the Comparator interface and defining the compare() method, we can specify how objects should be ordered based on specific attributes or data members. For example, we can create a Comparator for a Student class that compares students based on their GPA or age.

Syntax

public boolean equals(Object obj)

 

Return Value 

  • true: If equals() returns true, it means that the two Comparator instances are the same and correspond to the same memory object.
     
  • false: If equals() returns false, it indicates that the two Comparator instances are not the same and correspond to different objects in memory.

Java Comparator Example

Here is an example of how to use the Java Comparator Interface: 

  • Java

Java

import java.util.Comparator;

class LengthComparator implements Comparator<String> {
   public int compare(String str1, String str2) {
       return Integer.compare(str1.length(), str2.length());
   }

   public boolean equals(Object obj) {
       return this == obj;
   }
}

class HelloWorld {
   public static void main(String[] args) {
       LengthComparator comparator = new LengthComparator();

       String string1 = "Coding";
       String string2 = “Ninjas";

       int result = comparator.compare(string1, string2);
       boolean isEqual = comparator.equals(comparator);

       System.out.println("Comparison result: " + result);
       System.out.println("Are Comparators equal? " + isEqual);
   }
}

Output

Comparison result: 0
Are Comparators equal? true
 

 

In this example, we have a custom LengthComparator class that implements the Comparator interface and is used to compare the lengths of String objects. The compare() method compares the lengths of two strings by calling “Integer.compare()”. The equals() method simply determines whether the two comparator instances (this and obj) are equal.

 

In the main() method, we build a comparator instance of the LengthComparator class. In addition, we make two String objects, string1, and string2. We compare their lengths using the compare() method and save the result in the result variable. Because the length of both strings is equal, therefore the output is 0. The equals() method is then used to determine whether the comparator is equal to itself, and the result is placed in the isEqual variable. Because this and obj are referring to the same memory location, therefore the output is true.

Java Comparator Interface to Sort an Object

We can sort objects in Java using custom logic. We can do this by overriding compare method in the Comparator interface.

  • Java

Java

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class HelloWorld {
   public static void main(String[] args) {
       List<Integer> arr = new ArrayList<>();
       arr.add(2);
       arr.add(0);
       arr.add(6);
       arr.add(3);
       arr.add(9);
      
       // Sort the list in descending order
       Collections.sort(arr, new Comparator<Integer>() {
           @Override
           public int compare(Integer num1, Integer num2) {
               // Sorting in descending order
               return num2-num1;
           }
       });
       System.out.println(arr);
   }
}

Output:

[9, 6, 3, 2, 0]

 

Explanation: 

In the example above, we have an array list named arr. After inserting sufficient elements, we override the compare function of the Comparator interface. To implement descending order logic, we return num2-num1. The compare method is supposed to return positive and negative or zero. It will be only positive if the second parameter is greater than the first one, which basically translates to num2 being supposed to place before num1.

Java Comparable Vs Java Comparator

Here’s a detailed difference between comparable and comparator in Java:

 ComparableComparator
ObjectiveIt defines the natural order of objects within the class.It provides custom comparison logic to sort objects.
ImplementationIt requires modification of the class.compare() method of the Comparator Interface gets overridden.
InterfaceThe class itself implements it.It is implemented separately.
Methodpublic int compareTo(Object obj)public int compare(Object obj1, Object obj2):
Null ValuesNull values should be handled by the compareTo() method.Null values will be handled as per the custom logic defined.
Multiple ImplementationOnly one natural ordering can be defined per class.Multiple implementations can be defined.

Frequently Asked Questions

What is a Comparable interface in Java?

The Comparable interface in Java is used to define a natural ordering for a class. It requires implementing the compareTo() method to allow objects of the class to be compared and sorted.

What is the Comparator functional interface?

The Comparator functional interface in Java provides a way to define custom comparison logic for classes that do not implement Comparable. It allows sorting and comparison of objects based on specific criteria defined by the programmer.

Why use a Comparable interface in Java?

The Comparable interface is used in Java to establish a natural ordering for objects of a class. This enables sorting collections of objects and provides a standard way to compare instances of the class.

When to use Comparator?

Comparator is used in Java when you need to define custom sorting logic for classes that do not implement Comparable, or when you want to sort objects based on criteria other than their natural ordering. It allows flexible and customizable comparison behavior.

Conclusion

This article covered everything you needed to know about Java Comparator Interface in Java Collection. We covered its methods, compare and equals with examples. We also saw how to perform sorting using a comparator and the difference between comparable and comparator.

Recommended Readings:

 

Do check out some of the Popular Interview Problems from Top companies like AmazonAdobeGoogle, etc., on Naukri Code 360.

Cheers!

Previous article
BigInteger in Java
Next article
Singleton Class in java
Live masterclass