Table of contents
1.
Introduction
2.
Difference Between Comparable and Comparator
3.
What is Comparable in Java?
3.1.
compareTo Method
3.2.
Java
3.3.
Example
3.4.
Java
4.
What is Comparator in Java?
4.1.
compare() Method
4.2.
equals() Method
4.3.
Example
4.4.
Java
5.
Frequently Asked Questions
5.1.
Is Comparator a functional interface?
5.2.
Why is the comparator interface used?
5.3.
What is the application of a comparator?
5.4.
What is the function of the comparator?
5.5.
What is meant by comparable in Java?
6.
Conclusion
Last Updated: Mar 27, 2024
Medium

Difference between Comparable and Comparator

Author Aditya Gupta
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Hey there! You can quickly sort things like numbers and letters using a computer program called Java. But what if you want to sort things like students or libraries? That's when you must use "comparables" and "comparators". These are two ways that Java can sort these particular things. "Comparables" are already built into the object you want to sort, like a student's name or age. They help Java know how to sort the object. "Comparators" are special classes that you make to sort things differently. They allow you to sort objects in a way that is different from the natural way, like sorting students by their age instead of their names.

Difference between Comparable and Comparator

So, the main difference between "comparables" and "comparators" is that "comparables" are already built into the object you want to sort. In contrast, "comparators" are special classes you make to sort things differently. It's important to understand these ideas if you want to be good at using Java to sort objects like students and libraries.

Also, see Duck Number in Java and Hashcode Method in Java

Difference Between Comparable and Comparator

Overall,  The Key differences between Comparable and Comparator are given below.

 

Comparable

Comparator

Interface

java.lang.Comparable<T>

java.util.Comparator<T>

Purpose

Comparable defines the natural ordering of objects of a class

Comparator allows for custom ordering of objects of a class

Method

int compareTo(T o)

int compare(T o1, T o2)

 Returns

Comparable uses negative, zero, or positive integers to indicate ordering

Comparator uses negative, zero, or positive integers to indicate ordering

  Comparable object

The object being compared

N/A

  Comparator object

N/A

The Comparator order object is used to compare other objects

  Use case

Comparable sorts objects of a class by their natural ordering

Comparator sorts objects of a class by a custom ordering

   Examples

Comparable examples are sorting numbers or strings in ascending/descending order

Comparator examples are sorting objects by different criteria, e.g. name or age

What is Comparable in Java?

The Java programming language has an interface called Comparable that offers a natural ordering of things. It is widely used in many applications and is an essential component of the Java Collections Framework. An overview of the Java Comparable interface, its applications, and how to utilize it are all covered in this blog post.

A single method called compareTo exists in the Comparable interface; it accepts a single parameter of type T and returns an integer value. The compareTo method's returned integer can mean one of the following things:

  • If the number is negative, the object being compared is smaller than the parameterised object.
     
  • If the integer is 0, the two items under comparison are equal.
     
  • The object being compared to the object supplied as a parameter is larger if the integer is positive.
     

An object must be compared to another of the same type for a class to implement the Comparable interface. If the object is a negative integer, the compareTo method should return one.

compareTo Method

The compareTo() method is used to compare two objects based on their natural ordering. It is a method of the Comparable interface in Java.

  • Java

Java

public int compareTo(Person other) {
if (this.age < other.age) {
return -1;
}
else if (this.age > other.age) {
return 1;
}
else {
return 0;
}
}
You can also try this code with Online Java Compiler
Run Code

Example

consider a class called ‘Person’ that has two fields, ‘name’ and ‘age’. We can implement the Comparable interface for the ‘Person’ class by defining the compareTo method:

  • Java

Java

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
   public static void main(String[] args) {
       List<Person> people = new ArrayList<>();
       people.add(new Person("Alice", 25));
       people.add(new Person("Bob", 30));
       people.add(new Person("Charlie", 20));

       Collections.sort(people);
       for (Person person : people) {
           System.out.println(person.getName() + " " + person.getAge());
       }
   }

   public static class Person implements Comparable<Person> {
       private String name;
       private int age;

       public Person(String name, int age) {
           this.name = name;
           this.age = age;
       }

       public String getName() {
           return name;
       }

       public int getAge() {
           return age;
       }

       @Override
       public int compareTo(Person other) {
           if (this.age < other.age) {
               return -1;
           } else if (this.age > other.age) {
               return 1;
           } else {
               return 0;
           }
       }
   }
}
You can also try this code with Online Java Compiler
Run Code


Output:

output1

The compareTo method was used in the example above to compare Person objects according to their ages. We return -1 if the age of the current item is younger than the age of the other object. We return 1 if the age of the current item is older than the age of the other object. If not, we provide 0 as a sign that the two items are equal.

After a class has implemented the Comparable interface, collections of its objects can be sorted using the Java Collections Framework's sorting methods. A List of Person objects, for instance, can be sorted by invoking the Collections.sort method as seen below:

List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 25));
people.add(new Person("Bob", 30));
people.add(new Person("Charlie", 20));

Collections.sort(people);


In the example above, three additional objects have been added to a List of Person objects. The list may then be sorted based on age using the Collections.sort method, which uses the compareTo method we defined in the Person class.

Finally, we may establish a natural ordering of objects using Java's Comparable interface, a strong tool. By implementing the Comparable interface, we may utilise the Java Collections Framework's sorting methods to arrange collections of objects from our class according to the criteria of our choice.

Also see,  Swap Function in Java

What is Comparator in Java?

Java's Comparator interface allows users to compare items according to predetermined criteria. It offers a versatile technique to order things in a way that is useful to the user and is used to sort collections, arrays, and other data structures. The java.util package defines the Comparator interface with two methods: compare() and equals(). The Comparator interface's compare() function is the most crucial to compare two objects.

An integer value is returned by the compare() method, which takes two objects as inputs. The two items are arranged in this integer value's proper order. If the return value is negative, the first item is considered smaller than the second object. The two objects are regarded as equal if the return value is zero. If the return value is positive, the first item is considered bigger than the second object.

compare() Method

In Java, the compare() function is typically used as a static method in a class that implements the Comparator interface. The compare() function takes two objects of the same type and returns an integer value that indicates the order of the objects.

public int compare(T obj1, T obj2){
	return obj1.compareTo(obj2);
}

equals() Method

The equals() method in Java is used to compare two objects for equality.

public boolean equals(Object obj){
    if (obj == this) {
        return true;
    }
    if (!(obj instanceof Person)){
        return false;
    }
    Person other = (Person) obj;
    return this.name.equals(other.name) && this.age == other.age;
}

Example

Here is an example of a Comparator that compares two strings based on their length:

  • Java

Java

import java.util.Comparator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
   public static void main(String[] args) {
       List<String> strings = new ArrayList<>();
       strings.add("dog");
       strings.add("cat");
       strings.add("elephant");
       strings.add("bird");

       Comparator<String> comparator = new Comparator<String>() {
           @Override
           public int compare(String s1, String s2) {
               return Integer.compare(s1.length(), s2.length());
           }
       };

       Collections.sort(strings, comparator);
       System.out.println(strings);
   }
}
You can also try this code with Online Java Compiler
Run Code


Output:

output2

In this example, the StringLengthComparator class implements the Comparator interface and overrides the compare() method. The compare() method takes two strings as arguments and returns the difference between their lengths.

The list of strings, as you can see, has been arranged according to their length, with the shortest string (dog) showing first and the largest one (elephant) appearing last.

Finally, Comparator is a strong Java interface that enables developers to sort objects according to predefined criteria. It offers a versatile method for sorting collections, arrays, and other data structures in a way that makes sense to the developer. It's crucial to comprehend how the Comparator interface functions and how to apply it properly if you're dealing with Java.

Frequently Asked Questions

Is Comparator a functional interface?

Yes, Comparator is a Java functional interface that allows you to define unique comparison logic for sorting. It uses the "compare" abstract method.

Why is the comparator interface used?

Java uses the Comparator interface to offer objects that don't implement the Comparable interface with unique sorting logic.

What is the application of a comparator?

Custom sorting orders for objects can be defined via the Comparator interface, allowing for flexible sorting in collections and situations when natural ordering is not appropriate.

What is the function of the comparator?

When an object's inherent ordering is insufficient or improper, the Comparator interface defines the comparison logic for the object, enabling customized sorting in Java collections and other circumstances.

What is meant by comparable in Java?

In Java, Comparable is an interface that is used to define the natural ordering of a class. If a class implements the Comparable interface, it means that its objects can be compared to each other based on their natural order.

Conclusion

This article discusses the topic of Comparables and Comparators in Java. We hope this blog has helped you enhance your knowledge of the difference between comparable and comparator. If you want to learn more, then check out our articles.

And many more on our platform Coding Ninjas Studio.

Refer to our Guided Path to upskill yourself in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your coding ability, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio!

But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundles for placement preparations.

However, you may consider our paid courses to give your career an edge over others!

Happy Learning!

Live masterclass