Hi All,

Greeting of the day!

Today we will learn how to use comparator and comparable in sorting. Also, we will go through the differences between them.

So let's start,

Comparator and comparable both are interfaces used for comparison.

We will take 1 example of sorting a list of custom objects using different properties.

Now to use a Comparable interface for comparing and sorting we need to override

  public int compareTo(T o)

  • Compares this object with the specified object for order. 
  • compareTo method can returns  
    • negative integer  =if this object is less than the specified object
    • zero    =if this object is equal to specified object
    • positive integer  =if this object is greater than the specified object
Below is how we can override the compareTo method.

Sorting using an integer in descending order

Sorting using an integer in ascending order 

Sorting using String in ascending order

Sorting using String in descending order

A comparable interface is implemented at the class level so we can sort objects using a single property.
So let's sort the List of Products by productId using Comparable


Now let's create a list of products and try to sort it.
Below will be our output.

Now let's explore the Comparator interface.

Note - Before executing below examples remove implements Comparable<Product> and 
        @Override
public int compareTo(Product product) {
return this.productId-product.productId;
}
from Product.java

Using the Comparator interface we can sort lists by multiple properties and with Comparable we can sort by a single property it's the main difference between Comparator and Comparable.

Comparable is added at class level, Comparator is independent of class its another difference between them. 

We need to implement the below method for using the Comparator interface.
    
int compare(T o1, T o2)
 
Note this method compares its two-argument for ordering and returns below values
  • negative integer -if the first argument is less than the second.
  • zero-if first argument is equal to the second.
  • positive integer -if the first argument is greater than the second.
We need to create a separate class that will implement a Comparator interface for sorting based on different properties.

Example- PriceSorter.java to sort the list of products in ascending order by price

 Example 2 NameSorter to sort the list of products in descending order by name.

We need to pass an instance of NameSorter / PriceSorter as follows for sorting.


Note we can either use a comparator or a comparable.

Now, let's sort List using Java 8.

Here is output

Let me know if you have any questions.

Other articles you can refer

For spring visit Spring Tutorial

Thank you!
Happy Learning !!