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. | Comparator | Comparable |
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.