Posts which you will also like.

Saturday, August 18, 2012

JAVA Tutorial:Sorting list using comparator and comparable interface

In this Java Tutorial We are going to discuss about the ways in which we can do the sort the objects of our own classes using comparator and comparable interfaces.

Some times we come across scenarios in which we needs to sort a list of non primitive  object.Suppose you created a class Employee and now you want to sort the list of employees based on their salary or say based on their name or in tons of other parameter.
Java provides us a very simple and efficient way to do it ,using utility classes(inside util packages).
So we can take the help of methods of Collections or Arrays utility class.Now see the signature of the sort methods provided by these two classes to get to know about Comparable and Comparator interfaces.

1.Collections sort method:
  • void sort(List<T> list): This says that hey! pass me the List containing the objects to sort but ensure that objects must also tell me the attribute based on which sorting needs to be done.This condition can be fulfilled by implementing the interface Comparable and overriding its compareTo() method by the class whose objects we want to sort.Problem with this way of sorting is that we can sort using only one way since a class can implement a interface only one. 
  • void sort(List<T>list,Comparator<? super T> comp):This provides the solution to previous drawback.Just visualize what sort method says in this case.It says: I need the list of object to be sorted plus an implementation of Comparator interface.So we have to create an extra class which implements the Comparator interface and overrides the compare() method.You may ask what is the benefit of creating the extra class.Yes there is the benefit now we can do sorting based on multiple attributes(how?). I hope you got the answerSmile.Make sure to write import java.util.Comparator; to import Comparator.

2.Arrays sort method:
  • Arrays sort method supports only 2nd version i.e void sort(List<T>list,Comparator<? super T> comp) for objects.
  • It has lots of variations of sort methods for primitives.
Note: These sort methods are based on the merge sort algorithm.So if you need time and space complexity better than this you need to implement your own algorithm of sorting.
So lets proceed by creating our Employee class.In this example we will implement the Comparable interface.

package com.techy.rajeev;
public class Employee implements Comparable{
    private String ename;
    private int eid;
    private double salary;
    public Employee(String ename, int eid, double salary) {
        this.ename = ename;
        this.eid = eid;
        this.salary = salary;
    public String getEname() { return ename; } 
    public void setEname(String ename) {
        this.ename = ename;

    public int getEid() {
        return eid;

    public void setEid(int eid) {
        this.eid = eid;

    public double getSalary() {
        return salary;
    public void setSalary(double salary) {
        this.salary = salary;
    public String toString() {
        return "Employee [ename=" + ename + ", eid=" + eid + ", salary="
                + salary + "]";

@Override public int compareTo(Employee o) { //We are sorting based on the employee name return ename.compareTo(o.getEname()); } }

Now lets do the sorting and displaying it.

javapackage com.techy.rajeev;
import java.util.*;
public class TestSorting {
    public static void main(String[] args) {
        ArrayList<Employee>al=new ArrayList<Employee>();
        al.add(new Employee("Anonymous",1,12345.00));
        al.add(new Employee("Hacker",2,32423));
        al.add(new Employee("cba",3,23434));
        al.add(new Employee("ebc",4,32432));



Before:[Employee [ename=Anonymous, eid=1, salary=12345.0], Employee [ename=Hacker, eid=2, salary=32423.0], Employee [ename=Cba, eid=3, salary=23434.0], Employee [ename=Ebc, eid=4, salary=32432.0]]

After:[Employee [ename=Anonymous, eid=1, salary=12345.0], Employee [ename=Cba, eid=3, salary=23434.0], Employee [ename=Ebc, eid=4, salary=32432.0], Employee [ename=Hacker, eid=2, salary=32423.0]]

This was the sorting using Comparable interface.Now you can try the sorting using Comparator or keep reading,I will provide the implementation in next Java Tutorial on using Comparator .

No comments:

Post a Comment

Your comment may wait for moderation.... Protected by Copyscape Online Plagiarism Tool