Another good way to do this, which is a bit more flexible if there is more than one property of an object that you might want to sort, is to use Guava Ordering with its onResultOf(Function) option. This is ideal for sorting by property, since Function can be used to retrieve and return a specific property of an object. For a simple example, imagine a Person class with the String getFirstName() and String getLastName() methods.
List<Person> people = ...; Collections.sort(people, Ordering.natural().onResultOf( new Function<Person, String>() { public String apply(Person from) { return from.getFirstName(); } }));
The above will sort the list by name.
To make it more enjoyable, you can define functions that you might want to use as public static final fields in the Person class. Then you can sort by last name as follows:
Collections.sort(people, Ordering.natural().onResultOf(Person.GET_LAST_NAME));
As a wonderful note, all this will be much easier in Java 8 with lambda expressions and method references. You can write something like this without having to define clumsy anonymous inner classes or static end fields:
import static java.util.Comparator.comparing; ... people.sort(comparing(Person::getLastName));
Colind
source share