×

Comparator vs Comparable in Java

Comparator Vs Comparable in Java

In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types of objects that are not comparable, Java provides Comparator and Comparable interfaces.

Sorting Primitive data types

To sort primitive data types like integer array and String array, Java provides Arrays.sort() method. The following program demonstrates the use of the sort() method.

SortingPrimitivedt.java

 import java.util.*;
public class SortingPrimitivedt
{
    /* Driver Code */
public static void main(String ar[])
    {
        int[] intarray = {5,9,6,12};
System.out.println("Before Sorting integer array: "+Arrays.toString(intarray));
/* sorting integer array. */
Arrays.sort(intarray);
System.out.println("After Sorting integer array: "+Arrays.toString(intarray));
        String[] strarray = {"A", "K", "B", "H", "E"};
System.out.println("Before Sorting String array: "+Arrays.toString(strarray));
        /* sorting String array. */
Arrays.sort(strarray);
System.out.println("After Sorting String array: "+Arrays.toString(strarray));
    }
} 

Output:

 Before Sorting integer array: [5, 9, 6, 12]
After Sorting integer array: [ 5, 6, 9, 12]
Before Sorting String array: [A, K, B, H, E]
After Sorting String array: [A, B, E, H, K] 

Here, the intarray and strarray are sorted using Array.sort() method available in java.util package. And the result is displayed on the screen using the Arrays.toString() method.

Comparator

A Comparator is an interface declared in java.util package. It is used to order objects of a specific class. It has two methods,

compare(Object o1, Object o2) returns negative value, positive value or zero.

equals(Object o)returns true or false.

SampleComparator.java

 import java.io.*;
import java.util.*;
/* class Students implements Comparable. */
class Students implements Comparable<Students>
{
          private double average;
          private String name;
          private int year;
          /* Sorts students by year of passing */
          public int compareTo(Students m)
          {
                   return this.year - m.year;
          }
          /* Class constructor */
          public Students(String nm, double av, int yr)
          {
                   this.name = nm;
                   this.average = av;
                   this.year = yr;
          }
          /* methods for accessing private data of class variables */
          public double getAverage() { return average; }
          public String getName() { return name; }
          public int getYear()        { return year; }
}
/* Class to compare Students by Average CGPA */
class AverageCompare implements Comparator<Students>
{
          public int compare(Students m1, Students m2)
          {
                   if (m1.getAverage() < m2.getAverage())
                       return -1;
                   if (m1.getAverage() > m2.getAverage())
                       return 1;
                   else return 0;
          }
}
/* Class to compare Students by name */
class NameCompare implements Comparator<Students>
{
          public int compare(Students m1, Students m2)
          {
                   return m1.getName().compareTo(m2.getName());
          }
}
public class SampleComparator
{
    /* Driver Code */
          public static void main(String[] args)
          {
                   ArrayList<Students> list = new ArrayList<Students>();
                   list.add(new Students("Dipak", 9.3, 1999));
                   list.add(new Students("Anjali", 8.2, 1998));
                   list.add(new Students("Nikita", 7.8, 2000));
                   list.add(new Students("Rajesh", 8.9, 2002));
                   /* Sort by Average of Student */
                   System.out.println("Sorted by Average of Student:");
                   AverageCompareaverageCompare = new AverageCompare();
                   Collections.sort(list, averageCompare);
                   for (Students s : list)
                   System.out.println(s.getAverage() + " " +
                                                                   s.getName() + " " +
                                                                    s.getYear());
        /* Sort by Name of Student */           
                   System.out.println("\nSorted by Name of Student:");
                   NameComparenameCompare = new NameCompare();
                   Collections.sort(list, nameCompare);
                   for (Students s : list)
                    System.out.println(s.getName() + " " +
                                                                   s.getAverage() + " " +
                                                                   s.getYear());
                   /* Sort by Year of Passing */
                   System.out.println("\nSorted by Year of Passing:");
                   Collections.sort(list);
                   for (Students s : list)
                   System.out.println(s.getYear() + " " +
                                                                   s.getAverage() + " " +
                                                                   s.getName()+" ");
          }
} 

Output:

 Sorted by Average of Student:
7.8 Nikita 2000
8.2 Anjali 1998
8.9 Rajesh 2002
9.3 Dipak 1999
Sorted by Name of Student:
Anjali 8.2 1998
Dipak 9.3 1999
Nikita 7.8 2000
Rajesh 8.9 2002
Sorted by Year of Passing:
1998 8.2 Anjali
1999 9.3 Dipak
2000 7.8 Nikita
2002 8.9 Rajesh 

Here, class Students has members like average, name of student and year of passing. The interface Comparable is implemented in Students class and its method compareTo() is overridden in Students class.  The class SampleComparable implements the driver code.

Comparable

A Comparable is an interface declared in java.lang package. It compares objects of similar types. The compareTo() method is available in Comparable interface for performing the comparison operation.

SampleComparable.java

 import java.io.*;
import java.util.*;
import.java.lang.*;
// class Students that implements Comparable
class Students implements Comparable<Students>
{
          private double average;
          private String name;
          private int year;
          /* Used to sort Students by year of passing */
          public int compareTo(Students m)
          {
                   return this.year - m.year;
          }
          /* Class Constructor */
          public Students(String nm, double av, int yr)
          {
                   this.name = nm;
                   this.average = av;
                   this.year = yr;
          }
          /* methods for accessing private data of class Student */
          public double getAverage() { return average; }
          public String getName() { return name; }
          public int getYear()        { return year; }
}
public class SampleComparable
{
    /* Driver Code */
          public static void main(String[] args)
          {
                   ArrayList<Students> list = new ArrayList<Students>();
                   list.add(new Students("Dipak", 9.3, 1999));
                   list.add(new Students("Anjali", 8.2, 1998));
                   list.add(new Students("Nikita", 7.8, 2000));
                   list.add(new Students("Rajesh", 8.9, 2002));
                   System.out.println("Students Name after sorting : ");
                   for (Students s: list)
                   {
                             System.out.println(s.getName() + " " +s.getAverage() + " " +s.getYear());
                   }
          }
} 

Output:

 Students Name after sorting :
Dipak 9.3 1999
Anjali 8.2 1998
Nikita 7.8 2000
Rajesh 8.9 2002 

Here, class Students has members like average, name of student and year of passing. The interface Comparable is implemented in Students class and its method compareTo() is overridden in Students class.  The class SampleComparable implements the driver code.

Difference between Comparator and Comparable

Sr. No.ComparatorComparable
1.Comparator is declared in java.util package.Comparable is declared in java.lang package.
2.Comparator has compare() and equals() methods for sorting elements.Comparable has compareTo() method for sorting elements.
3.Comparator compares objects of two different classes.Comparable compares this referenced object with another specified object. 
4.Multiple sorting sequences are available in Comparator.Only a single sorting sequence is available in Comparable.
5.Comparators do not change the contents of the original class.Comparable affects the actual class by modifying its contents.

In this article, we have discussed Comparator and Comparable interfaces in Java. We have also understood the difference between both of these interfaces.


Related Topics

Java Pop

The array, linked list, stack, queue, and other data structures are supported by Java programming. The insertion, deletion, and element searching operations are available for every data structure. And Java...

4 minutes read.

Compare time in java

Introduction: This article discusses how to compare time in java. Maximum of the time we need to examine the date and datetime items. Date comparisons are vital if you want to...

3 minutes read.

Sliding Window Problem in Java

A sliding window is used in computer science and data science to process large datasets. It involves breaking the dataset into smaller chunks or windows and then processing it in...

6 minutes read.

Rectangular Numbers in Java

In this tutorial, we will understand the meaning of a rectangular number in Java with the aid of examples, illustrations, and implementations. It is one of the popular coding interview...

3 minutes read.

Differences between Set and List in Java

Set in Java: The Java. util package contains an interface called the set. The set interface expands the Collection interface. A collection interface is an unordered collection of List where duplicates...

6 minutes read.

Instanceof operator in Java

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). Because it compares the instance with type, the...

3 minutes read.

Collection Programs in Java

Collection Programs in Java Collection in Java provides a way to manipulate or store a group of objects. Each object in a collection is called element. Collection programs in Java mainly...

4 minutes read.

What’s New in Java 15

Sealed classes are the new concept that was introduced by Java 15. Sealed classes are a preview feature. Most of the features which are released in java 15 are in...

3 minutes read.

Program to Find the Common Elements between two Arrays in Java

In this article, we are going to learn how to find the common elements between two arrays using Java. Here, we use different approaches in Java to find the common...

3 minutes read.

Convert list to array Java

One of the popular collection interfaces for storing an ordered collection is the List. The List interface may contain repeating groups and preserves the insertion order of entries. This article will...

4 minutes read.

Java String indexOf() method

Java String indexOf() method returns index of a given character or substring present in a String. Methods Description int indexOf(int ch)     It returns index position for the given char value.int indexOf(int ch,...

2 minutes read.

Console Errors in Java

An unlawful motion taken through the person that reasons this system to act abnormally is amistake until this system is compiled or run; maximum programming mistakes pass unnoticed.The software is...

3 minutes read.

Design of JDBC

Java applications may interface using database systems from many vendors using the Java Database Connectivity (JDBC) Application Software Interface (API) from Sun Microsystem. To connect spreadsheets, JDBC and database drivers...

3 minutes read.

Java Integer numberOfLeadingZeros() method

The numberOfLeadingZeros()  method of Java Integer class returns the total number of zero bits preceding the highest-order one-bit in the 2’s complement binary representation of the specified int value.  Syntax public static...

1 minute read.

How to Calculate the Time Difference between Two Dates in Java?

The date is used extensively in Java to calculate date discrepancies. The date of joining an organization, admittance, appointment, etc., can be included when creating the application. The differences between...

4 minutes read.

Java Comparator Interface

Java comparator interface is used in a situation when we have to sort an object which does not implement Comparable or do sorting in a different way than the Comparable....

1 minute read.

Rehashing in Java

The most crucial idea mostly in the data structure is hashing, which is utilized to change a particular key into some other value. The hash function can be used to...

7 minutes read.

Constructor Overloading in Java

In Java, constructors can be overloaded just like methods. The idea of having multiple constructors with various parameter sets so that each function Object()  can carry out a particular task...

3 minutes read.

Difference between throw and throws in java

This article shows you the core difference between “throw” and “throws”keywords in Java programming language.The throw keyword tells Java you want another part of the code to deal withthe exception,...

2 minutes read.

Shallow copy in Java

Java's most important task is making a copy or clone of an object. In this part, we'll talk about shallow copies in Java and how to make them of Java...

4 minutes read.