Sorting Lists in Java with Comparators

August 31, 2014

I always forget how to write a comparator in Java, so here's an explanation for me to refer to.

You can sort a collection in Java using Collections.sort(), passing in the collection and a Comparator:

List<Person> lPeopleList = new ArrayList<Person>();
lPeopleList.add(new Person("Stephen", 20)); 
lPeopleList.add(new Person("Adam", 21)); 
lPeopleList.add(new Person("Charles", 22)); 
lPeopleList.add(new Person("Josh", 22));

Collections.sort(lPeopleList, new NameComparator());

Where the definition of NameComparator is:

class NameComparator implements Comparator<Person> 
{
  public int compare(Person pFirstPerson, Person pSecondPerson)
  {
    return pFirstPerson.name.compareToIgnoreCase(pSecondPerson.name);
  }
}

You can also implement your own sorting logic. This example sorts by age:

class NameComparator implements Comparator<Person> 
{
  public int compare(Person pFirstPerson, Person pSecondPerson)
  {
    if (pFirstPerson.age < pSecondPerson.age)
    {
      return -1; // second is larger
    }
    else if (pFirstPerson.age > pSecondPerson.age)
    {
      return 1; // first is larger
    }
    else
    {
      return 0; // values are the same
    }
  }
}

References