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
If you are using Java 8, you have 2 new static methods in the Comparator class, which come in handy:
public static Comparator nullsFirst(Comparator super T> comparator)
public static Comparator nullsLast(Comparator super T> comparator)
The comparison will be null safe and you can choose where to place the null values in the sorted sequence.
The following example:
List monkeyBusiness = Arrays.asList("Chimp", "eat", "sleep", "", null, "banana",
"throw banana peel", null, "smile", "run");
Comparator super String> comparator = (a, b) -> a.compareTo(b);
monkeyBusiness.stream().sorted(Comparator.nullsFirst(comparator))
.forEach(x -> System.out.print("[" + x + "] "));
will print: [null] [null] [] [Chimp] [banana] [eat] [run] [sleep] [smile] [throw banana peel]