Comparable vs Comparator

Comparable and comparator are interface which used to sort list of elements.

what is Comparable?

Comparable is a single sorting sequence that sort element on the basics of single element that may be id,name or age

It affect the original class.

It uses compareTo() method for sorting list of elements.

we can sort the element by Collections.sort(List list) method which is available for the Comparable from the main class.

Example for Comparable interface

import java.util.ArrayList;
import java.util.Collections;

class Employee
{
public static void main(String args[])
{
ArrayList<Student> obj = new ArrayList<>();
obj.add(new Student("Pandiyan",12));
obj.add(new Student("Prakash",10));
Collections.sort(obj);
for(Student st:obj)
{
System.out.println("Age--"+st.age);
}
}
static class Student implements Comparable<Student>
{
String name;
int age;
Student(String name,int age)
{
this.name = name;
this.age= age;
}
@Override
public int compareTo(Student student)
{
if(age == student.age)
return 0;
else if(age > student.age)
return 1;
else
return -1;
}
}
}

what is Comparator?

Comparator is a multiple sorting sequence that sort list of element on the basic of multiple element ie id,name or age.

It uses compare() method to sort the element.

It doesnt affect the original class.

we can sort the element by Collections.sort(List list,Comparator) method which is available for the Comparator from the main class.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

class Employee
{
public static void main(String args[])
{
ArrayList<Student> obj = new ArrayList<>();
obj.add(new Student("Pandiyan",12));
obj.add(new Student("Prakash",10));
Collections.sort(obj,new AgeCompare());
for(Student st:obj)
{
System.out.println("Age--"+st.age);
}
}
static class Student
{
String name;
int age;
Student(String name,int age)
{
this.name = name;
this.age= age;
}
}
//Sorting based on Age
static class AgeCompare implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
if (s1.age == s2.age)
return 0;
else if (s1.age > s2.age)
return 1;
else
return -1;
}
}
}

Major difference between both is by using compartator we can compare multiple element without modifying the pojo class and by making just separate comparator class alone but in comparable we have to modify the class and we cannt compare multiple elements.