Guava: Elegant Collection Ordering

PROBLEM

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>() {
    @Override
    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.

SOLUTION

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

List<Request> allRequests = ...;

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

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s