Sort a collection.
Consider a model class Person with property name,age and date of birth.
class Person {
public String name;
public int age;
public Date dob;
}
Consider a list of Person object.
There are two ways to sort the list . Using Comparator or Comparable.
public sortList() {
List<Person> personList = getListofPerson(); // some method to get the list.
//sort by name;
Collections.sort(personList, new Comparator<Person>() {
public int compare(Person e1, Person e2) {
return e2.name.compareTo(e1.name);
}});
// sort by age
Collections.sort(personList, new Comparator<Person>() {
public int compare(Person e1, Person e2) {
if (e1.age > e2.age )
return 1;
if (e1.age < e2.age)
return -1;
else
return 0;
}});
}