Possible Duplicate:
Sorting Java objects using multiple keys
I can’t find any example of using this method, all examples give the second parameter “null”.
I heard that this method used for sorting classes according to more than one criterion but no example where found.
public class Student implements Comparable<Student> {
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return name + ":" + age;
}
@Override
public int compareTo(Student o) {
Integer myAge = age;
Integer oAge = o.age;
return myAge.compareTo(oAge);
}
}
for this class if i want to sort a list of Student according to their names & ages how can i use the method Collections sort(List,Comparator)
Building upon your existing Student class, this is how I usually do it, especially if I need more than one comparator.
Usage:
EDIT
Since the release of Java 8 the inner class
Comparatorsmay be greatly simplified using lambdas. Java 8 also introduces a new method for theComparatorobjectthenComparing, which removes the need for doing manual checking of each comparator when nesting them. Below is the Java 8 implementation of theStudent.Comparatorsclass with these changes taken into account.