Sunday, February 16, 2014

Sorting Collections

Sorting of Java Objects in Collections is done in two ways.They are:

1)Implementing Comparable interface :

           Comparable Interface in java is used to define the natural sort order of a class.It is defined in lang package.Comparable interface provides one method "compareTo()" to implement in any class so that two instances of that class can be compared. compareTo() method compares the two object of the same type and returns a numerical result based on  the comparison.

In a Student list if we need to sort the list, based on the student roll no, its best  way to implement with Comparable interface.

Example :

public class Student implements Comparable {
private int rollNo;
private String firstName;
private String lastName;
// getter and setter for the properties
@Override
public int compareTo(Student s) {
return this.rollNo- s.rollNo;
}
}

Usage:
   List studentList=new ArrayList();
     //add student objects to studentList 
       Collections.sort(studentList);



2)Implementing Comparator interface :

          Comparator interface is used to order the objects of user-defined class.It is defined in util package.it provides multiple sorting sequence i.e. you can sort the elements based on any data member. Comparators can also be used to control the order of certain structures(such as TreeSet or TreeMap). For instance it may be rollno, name, age or anything else.             

This method is more like generics type if you have to sort with more option.
1) sort based on the firstNamne
2) sort based on the lastName

Example :

Sorting student collection by firstName.

public class FirstNameSorter implements Comparator{
@Override
public int compare(Student s1, Student s2) {
return s1.getFirstName().compareTo(s2.getFirstName());
}


Usage:
List studentList=new ArrayList();
     //add student objects to studentList 
       Collections.sort(studentList, new FirstNameSorter());


Sorting student collection by lastName.

public class LastNameSorter implements Comparator{
@Override
public int compare(Student s1, Student s2) {
return s1.getLastName().compareTo(s2.getLastName());
}
}

Usage:
     List studentList=new ArrayList();
     //add student objects to studentList 
    Collections.sort(studentList, new LastNameSorter());