Java: Sorting List with Comparator
August 18th, 2009 by jeremychoneclass EmpSortByName implements Comparator{
public int compare(Employee o1, Employee o2) {
return o1.getName().compareTo(o2.getName());
}
}
....
List employees = ...;
Collections.sort(employees , new EmpSortByName());
java.lang.Comparable: int compareTo(Object o1)
This method compares this object with o1 object. Returned int value has the following meanings.
- positive – this object is greater than o1
- zero – this object equals to o1
- negative – this object is less than o1
java.lang.Comparator: int compare(Object o1, Objecto2)
This method compares o1 and o2 objects. Returned int value has the following meanings.
- positive – o1 is greater than o2
- zero – o1 equals to o2
- negative – o1 is less than o1