Comparable and Comparator Interfaces
This is one of the most important repeatedly asked question in java. In this blog, i have covered how to do customized sorting by using the Comparable and Comparator interface
Comparator Interface
It is used for Customised sorting for array of objects
we can write this without disturbing the actual class, suppose if we want without the interference of legacy class
it is found in java.util package. it has compare method which will take 2 arguments
public int compare(Object obj1, Object obj2):
// Java Program to Demonstrate Working of
// Comparator Interface
// Importing required classes
import java.io.*;
import java.lang.*;
import java.util.*;
// Class 1
// A class to represent a Student
class Student {
// Attributes of a student
int rollno;
String name, address;
// Constructor
public Student(int rollno, String name, String address)
{
// This keyword refers to current instance itself
this.rollno = rollno;
this.name = name;
this.address = address;
}
// Method of Student class
// To print student details in main()
public String toString()
{
// Returning attributes of Student
return this.rollno + " " + this.name + " "
+ this.address;
}
}
// Class 2
// Helper class implementing Comparator interface
class Sortbyroll implements Comparator<Student> {
// Method
// Sorting in ascending order of roll number
public int compare(Student a, Student b)
{
return a.rollno - b.rollno;
}
}
// Class 3
// Helper class implementing Comparator interface
class Sortbyname implements Comparator<Student> {
// Method
// Sorting in ascending order of name
public int compare(Student a, Student b)
{
return a.name.compareTo(b.name);
}
}
// Class 4
// Main class
class DriverClass {
// Main driver method
public static void main(String[] args)
{
// Creating an empty ArrayList of Student type
ArrayList<Student> ar = new ArrayList<Student>();
// Adding entries in above List
// using add() method
ar.add(new Student(111, "Sunil", "Britan"));
ar.add(new Student(130, "Kiran", "USA"));
ar.add(new Student(121, "John", "Canada"));
ar.add(new Student(177, "James", "Hongkong"));
// Display message on console for better readability
System.out.println("Unsorted list");
// Iterating over entries to print them
for (int i = 0; i < ar.size(); i++)
System.out.println(ar.get(i));
// Sorting student entries by roll number
Collections.sort(ar, new Sortbyroll());
// Display message on console for better readability
System.out.println("\nSorted by rollno");
// Again iterating over entries to print them
for (int i = 0; i < ar.size(); i++)
System.out.println(ar.get(i));
// Sorting student entries by name
Collections.sort(ar, new Sortbyname());
// Display message on console for better readability
System.out.println("\nSorted by name");
// // Again iterating over entries to print them
for (int i = 0; i < ar.size(); i++)
System.out.println(ar.get(i));
}
}
Method 1: Implementing Comparator Interface by using Lambda Expression
Comparator<Student> comp=(s1,s2)->(s1.id<s2.id)?-1:(s1.id>s2.id)?1:0;
Collection.sort(al,comp);
for(Student st:al){
System.out.println(st.id+" "+st.name+" "+st.country);
}
Method 2: Implementing Comparator Interface by using Anonymous Inner class
Comparator<Student> comp =new Comparator<>(){
public int compare(Student s1,Student s2){
return s1.id-s2.id;
}
};
Collection.sort(al,comp);
for(Student st:al){
System.out.println(st.id+" "+st.name+" "+st.country);
}
Method 3: Implementing Comparator Interface by passing directly as an argument for sort function
Anonymous Inner class :
Collections.sort(ar,new Comparator<>(){
public int compare(Student s1,Student s2){
return s1.id-s2.id;
}
});
Lambda Expression :
Collections.sort(ar,((s1,s2)->(s1.id<s2.id)?-1:(s1.id>s2.id)?1:0));
for(Student st:ar){
System.out.println(st.id+" "+st.name+" "+st.country);
}
Comparable Interface
Comparable interface its mostly used for natural sorting for array of Objects ,
Its a single sorting sequence ie we can sort by using only 1 parameter of the object.
Its found in Java.lang package. it contains compareTo method which accepts only 1 argument
compareTo(Object obj) method public int compareTo(Object obj): It is used to compare the current object with the specified object. It returns
positive integer, if the current object is greater than the specified object.
negative integer, if the current object is less than the specified object.
zero, if the current object is equal to the specified object.
import java.util.*;
class Student implements Comparable<Student>{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
public int compareTo(Student st){
if(age==st.age)
return 0;
else if(age>st.age)
return 1;
else
return -1;
}
}
public class TestSort1{
public static void main(String args[]){
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(100,"Sunil",23));
al.add(new Student(101,"Kiran",37));
al.add(new Student(102,"Nick",21));
Collections.sort(al);
for(Student st:al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}