Java gives very convenient way for sorting collection types by Collections.sort method. It have two flavors
- Collections.sort( collection, new Comparator < T>( )){}
This is runtime sorting, & you will create an anonymous class implementation and will override Comparator’s compare method and return value -1, 0 , 1. - Collections.sort( collection)
You provide collection whose objects implemented Comparable or Comparator interface and provide overridden method.
Let’s we have Student class as below,
class Student {
private String name;
private Integer id;
private String rollNo;
private Long grade;
//getters & setters
}
Sometimes we want to sort it by name, sometimes by grade & sometimes by rollNo. So we can’t implement Comparable or Comparator to fix the sorting field. We will sort the objects dynamically.
public class JavaTest {
public static void main( String [ ] args ) {
List < Student > studentList = new ArrayList < Student >( );
studentList.add( new Student( "Mark", 5L ) );
studentList.add( new Student( "John", 3L ) );
studentList.add( new Student( "Faisal", 6L ) );
studentList.add( new Student( "Keat", 4L ) );
Collections.sort( studentList, new Comparator < Student >( ) {
public int compare( Student student1, Student student2 ) {
return student1.getGrade( ).compareTo( student2.getGrade( ) );
}
} );
for ( Student student : studentList ) {
System.out.println( "Student Name: " + student.getName( ) + " : " + student.getGrade( ) );
}
}
}
The above class is just a snapshot view, about how we sort a collection runtime, where we need it. We can sort by any field/attribute just by creating anonymous class and changing variable in compare method. That’s all. C YA Next time with another recipe.
