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);
</request,>
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