×

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 Program to remove duplicate characters in a string

In strings, we can find many characters present one or more times in a string; accessing a particular character is difficult due to repetition. Duplicate characters will present in the...

5 minutes read.

Java Serialization

JAVA SERIALIZATION Serialization is a process by which objects can be represented as a sequence of bytes. These bytes have information about object's data, object's type and datatypes of members in...

3 minutes read.

PriorityBlockingQueue Class in Java

What is the Queue? An abstract data structure like Stacks is a queue. A queue is open on both ends. Data is always pushed to one end, called enqueue, and removed...

4 minutes read.

Java List Interface

List interface is used when we have to order a collection which contains duplicate entries. Like an array, the elements of its implementation classes are retrieved and inserted at a...

2 minutes read.

Java String join() method

Java String join() method returns a joined String with given delimiter Syntax: public static String join(CharSequence delimeter,charSequence...elements) public static String join(CharSequence delimeter,Iterable<?extens charSequence>elements) Parameters: delimiter: char value to be added with each element elements: char value...

1 minute read.

Java Strictfp Keyword

Strictfp is used to impose limits on floating-point calculation. It ensures that we will get the same result on every platform while performing an operation with the floating-point variable. The floating-point calculation is platform-dependent due...

1 minute read.

Class vs Object in Java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Java Trim

Leading and leaving spaces are removed by the built-in Java String trim() method. Space seems to have the Unicode element of "x0040." Java trim() function looks for all of these...

3 minutes read.

What are Array strings in Java?

In normal programming, An array is a group and a collection of identical forms of data that are stored in a sequential memory region and may be accessed using their...

4 minutes read.

PriorityQueue in Java

PriorityQueue in Java A PriorityQueue is a member of the Java Collection Framework and is used when the values are needed to be processed based on priority. Priority queue operates similar to...

8 minutes read.

Race Condition in Java

Java is a multi-threaded programming language, race conditions are more likely to arise. Mostly because data can change when multiple threads visit the same resource simultaneously. Race conditions are concurrency...

3 minutes read.

Java this keyword

This Keyword in Java This keyword can be used in many different ways in Java. This is a reference variable in Java that points to the active object. In Java, the...

8 minutes read.

Java Strings

String class is the most used class in Java programming language. The string is the sequence of characters, which is treated as objects in Java. Creating String objects We create String objects...

5 minutes read.

How to declare string array in Java

Introduction Array is a data structure with a fixed size, which allows us to store elements of similar type. Data of primitive types like int, char, float, string, etc. can be...

2 minutes read.

How to compare characters in Java

In this tutorial, we will learn about how to compare characters in Java. To compare characters in Java, we will learn about what is a character in Java Char The character is...

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.

How to convert float to String in Java

How to convert float to String in java There are following methods to convert float to String: Convert using Float.toString(float) Convert using String.valueOf(float) Convert using Float.toString(float) The Float class has a static method that returns...

2 minutes read.

Java Boolean getBoolean() Method

The getBoolean() method of Java Boolean class returns true if the specified system property is not null and is equal to the String ‘true’, else the result returned is false. Syntax public...

1 minute read.

JDBC Architecture

JDBC: JDBC stands for Java Database Connectivity. Sun Microsystems has a specification called JDBC. JDBC is a Java API (Application Programming Interface) that enables users to interact or communicate with...

4 minutes read.

Balanced Prime Number in Java

This section will cover the definition of a balanced prime number as well as how to find one using a Java program. Balance Prime Number A prime number that is equivalent to...

5 minutes read.