Sunday 6 April 2014

Sorting in List using Comparator and Comparable

You must have been came across the situation where you have to sort a collection of objects by a certain rule. And if you are working on a domain where people are your main entities, you will encounter it more. There must be many ways to it, which ranges from sorting on client UI using javascript to sorting on server side using complex algorithm, and sometimes in database too.
If you do not have millions of records to play with at a time then for sorting i will recommend you to consider comparable or comparator interface.
1. Comparable
Comparable is implemented by a class in order to be able to comparing object of itself with some other objects. The class itself must implement the interface in order to be able to compare its instance(s). The method required for implementation is compareTo(). Here is an example to show the usage:
package com.skc.compare;

public class StudentCompare implements Comparable<StudentCompare> {

 private int studentId;
 private String studentName;
 private String studentStd;

 public StudentCompare(int studentId, String studentName, String studentStd) {
  super();
  this.studentId = studentId;
  this.studentName = studentName;
  this.studentStd = studentStd;
 }

 public int getStudentId() {
  return studentId;
 }

 public void setStudentId(int studentId) {
  this.studentId = studentId;
 }

 public String getStudentName() {
  return studentName;
 }

 public void setStudentName(String studentName) {
  this.studentName = studentName;
 }

 public String getStudentStd() {
  return studentStd;
 }

 public void setStudentStd(String studentStd) {
  this.studentStd = studentStd;
 }

 @Override
 public String toString() {
  return "Student Id :" + this.getStudentId() + " Student Name : "
    + this.getStudentName() + " Student Standard : "
    + this.getStudentStd();
 }

 @Override
 public int compareTo(StudentCompare skc) {
  // TODO Auto-generated method stub
  return this.getStudentId() < skc.getStudentId() ? -1 : (this
    .getStudentId() > skc.getStudentId() ? 1 : 0);
 }

}
package com.skc.compare;

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

public class StudentCompareDemo {
 public static void main(String[] args) {
  List<StudentCompare> studentList = new ArrayList<StudentCompare>();
  studentList.add(new StudentCompare(10,"SKC","B.Tech"));
  studentList.add(new StudentCompare(20,"SKC1","M.Tech"));
  studentList.add(new StudentCompare(11,"SKC2","B.Tech"));
  studentList.add(new StudentCompare(9,"SKC3","M.Tech"));
  studentList.add(new StudentCompare(26,"SKC4","MS"));
  studentList.add(new StudentCompare(1,"SKC5","BS"));
  for (StudentCompare skc:studentList) {
   System.out.println(skc);
  }
  System.out.println("After Sort");
  Collections.sort(studentList);
  for (StudentCompare skc:studentList) {
   System.out.println(skc);
  }
 }
}
Here, We can able to compare to a single field of a Class and We can able to sort in this way.If We have requirement to sort with any property, then we'll go for Comparator.

2. Comparator
Comparator is capable if comparing objects based on different attributes. e.g. 2 men can be compared based on `name` or `age` etc. (this can not be done using comparable. )
The method required to implement is compare(). Now let’s use another way to compare those TV by size. The common use of Comparator is sorting. Both Collections and Arrays classes provide a sort method which use a Comparator.

package com.skc.compare;

public class Student {

 private int studentId;
 private String studentName;
 private String studentStd;

 public Student(int studentId, String studentName, String studentStd) {
  super();
  this.studentId = studentId;
  this.studentName = studentName;
  this.studentStd = studentStd;
 }

 public int getStudentId() {
  return studentId;
 }

 public void setStudentId(int studentId) {
  this.studentId = studentId;
 }

 public String getStudentName() {
  return studentName;
 }

 public void setStudentName(String studentName) {
  this.studentName = studentName;
 }

 public String getStudentStd() {
  return studentStd;
 }

 public void setStudentStd(String studentStd) {
  this.studentStd = studentStd;
 }

 @Override
 public String toString() {
  return "Student Id :" + this.getStudentId() + " Student Name : "
    + this.getStudentName() + " Student Standard : "
    + this.getStudentStd();
 }

}

package com.skc.compare;

import java.util.Comparator;

public class StudentNameComparator implements Comparator<Student> {

 @Override
 public int compare(Student stud1, Student stud2) {
  // TODO Auto-generated method stub
  return stud1.getStudentStd().compareTo(stud2.getStudentStd());
 }

}

package com.skc.compare;

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

public class StudentComparatorDemo {
 public static void main(String[] args) {
  List<Student> studentList = new ArrayList<Student>();
  studentList.add(new Student(13,"SKCA","A"));
  studentList.add(new Student(11,"SKCB","B"));
  studentList.add(new Student(15,"SKCC","C"));
  studentList.add(new Student(10,"SKCD","D"));
  studentList.add(new Student(12,"SKCE","E"));
  studentList.add(new Student(14,"SKCF","F"));
 
  Collections.sort(studentList, new StudentNameComparator());
  for(Student student : studentList){  System.out.println(student.getStudentId()+"\t"+student.getStudentName()+"\t"+student.getStudentStd());
  }
 }
}
I will recommend all to use Comparator Interface to implements the Sorting in List as we can sort by the help of any property by creating an Object of that class. If we'll use Comparable over there , It is something Hard-Coded.

Difference between Comparator and Comparable :
Parameter
Comparable
Comparator
Sorting logic
Sorting logic must be in same class whose objects are being sorted. Hence this is called natural ordering of objects
Sorting logic is in separate class. Hence we can write different sorting based on different attributes of objects to be sorted. E.g. Sorting using id,name etc.
Implementation

Class whose objects to be sorted must implement this interface.e.g Country class needs to implement comparable to collection of country object by id
Class whose objects to be sorted do not need to implement this interface.Some other class can implement this interface. E.g.-CountrySortByIdComparator class can implement Comparator interface to sort collection of country object by id
Sorting method
int compareTo(Object o1)
This method compares this object with o1 object and returns  a integer.Its value has following meaning
1. positive – this object is greater than o1
2. zero – this object equals to o1
3. negative – this object is less than o1
int compare(Object o1,Object o2)
This method compares o1 and o2 objects. and returns  a integer.Its value has following meaning.
1. positive – o1 is greater than o2
2. zero – o1 equals to o2
3. negative – o1 is less than o1
Calling method
Collections.sort(List)
Here objects will be sorted on the basis of CompareTo method
Collections.sort(List, Comparator)
Here objects will be sorted on the basis of Compare method in Comparator
Package
Java.lang.Comparable
Java.util.Comparator

No comments:

Post a Comment