We have some code which sorts a list of addresses based on the distance between their coordinates. this is done through collections.sort with a custom comparator.
How
Just to expand on Willi Schönborn's answer, I came here to say that google-collections is exactly what you're after here.
In the general case, you can just write your own Comparator to ignore nulls (assume non-null, so it can concentrate on the important logic), and then use Ordering to handle the nulls:
Collections.sort(addresses, Ordering.from(new AddressComparator()).nullsLast());
In your case, though, it's data WITHIN the Address (the Coordinates) that is being used to sort, right? google-collections is even more useful in this case. So you might have something more like:
// Seems verbose at first glance, but you'll probably find yourself reusing
// this a lot and it will pay off quickly.
private static final Function ADDRESS_TO_COORDINATES =
new Function() {
public Coordinates apply(Address in) {
return in.getCoordinates();
}
};
private static final Comparator COORDINATE_SORTER = .... // existing
then when you want to sort:
Collections.sort(addresses,
Ordering.from(COORDINATE_SORTER)
.nullsLast()
.onResultOf(ADDRESS_TO_COORDINATES));
and that's where the power of google-collections really starts to pay off.