Guava: Elegant Collection Ordering


Java provides a built-in API to sort a list, but it is flat out ugly and prone to error especially when dealing with Comparator. Here’s an example:-

List<request> allRequests = ...;

Collections.sort(allRequests, new Comparator<request>() {
    public int compare(Request lhs, Request rhs) {
        if (lhs.getSubmissionDatetime() == null) {
            return -1;
        else if (rhs.getSubmissionDatetime() == null) {
            return 1;

        return lhs.getSubmissionDatetime().compareTo(rhs.getSubmissionDatetime());

Number of puppies killed = 3 … from the if-else statement.


A better way to do this is to use Ordering from Guava:-

List<Request> allRequests = ...;
List<Request> sortedRequests = Ordering.natural()
        .onResultOf(new Function<Request, LocalDateTime>() {
            public LocalDateTime apply(Request request) {
                return request.getSubmissionDatetime();


In this example, we want all the null elements to appear on top of the list. We can also use nullsLast() if we want them to be at the bottom of the list.

Number of puppies killed = 0.

Leave a Reply

Your email address will not be published. Required fields are marked *