Comparable
and Comparator in Java are very useful for sorting collection of objects.
Java
provides Comparable interface which should be implemented by any custom class
if we want to use Arrays or Collections sorting methods. Comparable interface
has compareTo(T obj) method which is used by sorting methods, you can check any
Wrapper, String or Date class to confirm this. We should override this method
in such a way that it returns a negative integer, zero, or a positive integer
if “this” object is less than, equal to, or greater than the object passed as
argument.
Comparator
interface compare(Object o1, Object o2) method need to be implemented that
takes two Object argument, it should be implemented in such a way that it
returns negative int if first argument is less than the second one and returns
zero if they are equal and positive int if first argument is greater than
second one.
Comparable
and Comparator interfaces use Generics for compile time type checking.
Comparable Vs. Comparator
1.Comparable
interface is defined in java.lang package and Comparator interface is defined
in java.util package. Comparator is used as a utility for sort objects and
Comparable is provided by default because it is in java.lang package.
2.Comparable
interface has method public int compareTo(Object ob) which returns negative
integer, zero and positive integer when this reference object is less than
,equal and greater than with specified object in parameter. Comparator
interface has method public int compare(Object ob1,Object ob2) which returns
negative integer, zero and positive integer when first object(ob1) is less than
,equal and greater than with second object (ob2) in parameter.
3.Comparable
compares an object with this reference object and Comparator compares 2
provided objects.
4.If a class
implement Comparable interface, that object’s List or Array can be sorted by
using Collections.sort() or Arrays.sort()
according to the compareTo() method.
Comparator should implement within class or outside a class then give it to
sort method.
5.Objects
which implement Comparable in Java can
be used as keys in a SortedMap like TreeMap or elements in a SortedSet for example TreeSet, without specifying any
Comparator.
Example
I’m going to
explain these concepts using Student example.I have added
extra variable “place” where you can see the data sorted way.
import java.util.Comparator;
public class Student implements Comparable<Student>{
private int id;
private String name;
private int age;
private int place;//to identify the place change against the sort
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(int id, String name, int age, int place) {
super();
this.id = id;
this.name = name;
this.age = age;
this.place = place;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getPlace() {
return place;
}
public void setPlace(int place) {
this.place = place;
}
//implementation of compareTo method in Comparable interface
public int compareTo(Student s) {
return this.id-s.id;
}
//implementation of Comparator interface according to sort by age
public static Comparator<Student> ageComparator = new Comparator<Student>(){
public int compare(Student s0, Student s1) {
return s0.getAge()-s1.getAge();
}
};
//implementation of Comparator interface according to sort by name
public static Comparator<Student> nameComparator = new Comparator<Student>(){
public int compare(Student s0, Student s1) {
return s0.getName().compareTo(s1.getName());
}
};
//implementation of Comparator interface according to sort by id then name
public static Comparator<Student> idNameComparator = new Comparator<Student>(){
public int compare(Student s0,Student s1){
int flag = s0.id-s1.id;
if(flag == 0)
flag = s0.getName().compareTo(s1.getName());
return flag;
}
};
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + ",place = "+place+"]";
}
}
public class App
{
public static void main( String[] args )
{
testCompare();
}
public static void testCompare(){
Student s2 = new Student(2,"disa",24,1);
Student s5 = new Student(5,"ciri",20,2);
Student s3 = new Student(3,"amal",30,3);
Student s1 = new Student(1,"biri",10,4);
List<Student> al = new ArrayList<Student>();
al.add(s2);
al.add(s5);
al.add(s3);
al.add(s1);
System.out.println("Unsorted ArrayList");
for (Student s : al) {
System.out.println(s.toString());
}
System.out.println("");
System.out.println("Sorted using Comparable interface accroding to compareTo() method");
Collections.sort(al);
for (Student s : al) {
System.out.println(s.toString());
}
System.out.println("");
System.out.println("Sorted using Comparator interface accroding to ageComparator's compare() method");
Collections.sort(al,Student.ageComparator);
for (Student s : al) {
System.out.println(s.toString());
}
System.out.println("");
System.out.println("Sorted using Comparator interface accroding to nameComparator's compare() method");
Collections.sort(al,Student.nameComparator);
for (Student s : al) {
System.out.println(s.toString());
}
System.out.println("");
System.out.println("Sorted using Comparator interface accroding to idNameComparator's compare() method");
Collections.sort(al,Student.idNameComparator);
for (Student s : al) {
System.out.println(s.toString());
}
}
}
import java.util.Comparator;
public class Student implements Comparable<Student>{
private int id;
private String name;
private int age;
private int place;//to identify the place change against the sort
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(int id, String name, int age, int place) {
super();
this.id = id;
this.name = name;
this.age = age;
this.place = place;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getPlace() {
return place;
}
public void setPlace(int place) {
this.place = place;
}
//implementation of compareTo method in Comparable interface
public int compareTo(Student s) {
return this.id-s.id;
}
//implementation of Comparator interface according to sort by age
public static Comparator<Student> ageComparator = new Comparator<Student>(){
public int compare(Student s0, Student s1) {
return s0.getAge()-s1.getAge();
}
};
//implementation of Comparator interface according to sort by name
public static Comparator<Student> nameComparator = new Comparator<Student>(){
public int compare(Student s0, Student s1) {
return s0.getName().compareTo(s1.getName());
}
};
//implementation of Comparator interface according to sort by id then name
public static Comparator<Student> idNameComparator = new Comparator<Student>(){
public int compare(Student s0,Student s1){
int flag = s0.id-s1.id;
if(flag == 0)
flag = s0.getName().compareTo(s1.getName());
return flag;
}
};
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + ",place = "+place+"]";
}
}
public class App
{
public static void main( String[] args )
{
testCompare();
}
public static void testCompare(){
Student s2 = new Student(2,"disa",24,1);
Student s5 = new Student(5,"ciri",20,2);
Student s3 = new Student(3,"amal",30,3);
Student s1 = new Student(1,"biri",10,4);
List<Student> al = new ArrayList<Student>();
al.add(s2);
al.add(s5);
al.add(s3);
al.add(s1);
System.out.println("Unsorted ArrayList");
for (Student s : al) {
System.out.println(s.toString());
}
System.out.println("");
System.out.println("Sorted using Comparable interface accroding to compareTo() method");
Collections.sort(al);
for (Student s : al) {
System.out.println(s.toString());
}
System.out.println("");
System.out.println("Sorted using Comparator interface accroding to ageComparator's compare() method");
Collections.sort(al,Student.ageComparator);
for (Student s : al) {
System.out.println(s.toString());
}
System.out.println("");
System.out.println("Sorted using Comparator interface accroding to nameComparator's compare() method");
Collections.sort(al,Student.nameComparator);
for (Student s : al) {
System.out.println(s.toString());
}
System.out.println("");
System.out.println("Sorted using Comparator interface accroding to idNameComparator's compare() method");
Collections.sort(al,Student.idNameComparator);
for (Student s : al) {
System.out.println(s.toString());
}
}
}
Output
Unsorted ArrayList
Student [id=2, name=disa, age=24,place = 1]
Student [id=5, name=ciri, age=20,place = 2]
Student [id=3, name=amal, age=30,place = 3]
Student [id=1, name=biri, age=10,place = 4]
Sorted using Comparable interface accroding to compareTo() method
Student [id=1, name=biri, age=10,place = 4]
Student [id=2, name=disa, age=24,place = 1]
Student [id=3, name=amal, age=30,place = 3]
Student [id=5, name=ciri, age=20,place = 2]
Sorted using Comparator interface accroding to ageComparator's compare() method
Student [id=1, name=biri, age=10,place = 4]
Student [id=5, name=ciri, age=20,place = 2]
Student [id=2, name=disa, age=24,place = 1]
Student [id=3, name=amal, age=30,place = 3]
Sorted using Comparator interface accroding to nameComparator's compare() method
Student [id=3, name=amal, age=30,place = 3]
Student [id=1, name=biri, age=10,place = 4]
Student [id=5, name=ciri, age=20,place = 2]
Student [id=2, name=disa, age=24,place = 1]
Sorted using Comparator interface accroding to idNameComparator's compare() method
Student [id=1, name=biri, age=10,place = 4]
Student [id=2, name=disa, age=24,place = 1]
Student [id=3, name=amal, age=30,place = 3]
Student [id=5, name=ciri, age=20,place = 2]