Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparator with null values

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.

However from time to time an address without coordinates is in the list causing a NullPointerException. My initial idea to fix this was to have the comparator return 0 as distance for addresses where at least one of the coordinates is null. I fear this might lead to corruption of the order the 'valid' elements in the list.

so is returning a '0' values for null data in a comparator ok, or is there a cleaner way to resolve this?

like image 468
pvgoddijn Avatar asked Mar 08 '10 13:03

pvgoddijn


People also ask

How do you handle null in Comparator?

Comparator nullsLast() method in Java with examples When both elements are null, then they are considered equal. When both elements are non-null, the specified Comparator determines the order. If specified comparator is null, then the returned comparator considers all non-null elements equal.

How do you sort a list with null values?

We are sorting using the nullsFirst() method, after sorting, null values will come in the start and then the sorting list of employees will come sorted by date of birth. To sort on natural order, after ordering null values, use Comparator. nullsFirst( Comparator. naturalOrder() ).

How do you sort a list with null values in Java 8?

Java 8 – Sorting List of Integers with null values : Here, we are sorting list of integers which contains null values using static methods nullsFirst() & nullsLast() of Comparator interface. Comparator. nullsFirst() – this comparator helps to push null values to first/starting position.

Can we use compareTo in Comparator?

In Java, we can implement whatever sorting algorithm we want with any type. Using the Comparable interface and compareTo() method, we can sort using alphabetical order, String length, reverse alphabetical order, or numbers. The Comparator interface allows us to do the same but in a more flexible way.


1 Answers

Handle it like null means infinitely far away. Thus:

  • comp(1234, null) == -1
  • comp(null, null) == 0
  • comp(null, 1234) == 1

With this, you get a consistent ordering.

like image 64
Sjoerd Avatar answered Sep 22 '22 02:09

Sjoerd