Java: Sorting List with Comparator

August 18th, 2009 by jeremychone
class 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.

  1. positive – this object is greater than o1
  2. zero – this object equals to o1
  3. 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.

  1. positive – o1 is greater than o2
  2. zero – o1 equals to o2
  3. negative – o1 is less than o1

Source: Java Sorting: Comparator vs Comparable Tutorial

Leave a Reply