Monday, July 25, 2011

CODE TO SORT GENERIC LIST IN JAVA


List allStudents=Student.getStudentsByInstitution(instName);

               /*

Assume above line will give store few Student objects in allStudents list  so, here below code will sort all the Student objects in allStudents respective to firstname attribute

                                       */

Collections.sort(allStudents, new Comparator() {
public int compare(Object o1, Object o2) {
    Student s1 = (Student)o1;
    Student s2 = (Student)o2;
    String f1 = s1.getFirstName();
    String f2 = s2.getFirstName();  
    return f1.trim().compareToIgnoreCase(f2.trim());  
}
});

   for(Student studObj:allStudents) {
      out.println(" FirstName : "+studObj.getFirstName());
      out.println(" LastName : "+studObj.getLastName());
       ...........
       ...........
    }


No comments:

Post a Comment