comparator with null values

前端 未结 9 1154
萌比男神i
萌比男神i 2020-12-04 16:25

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

9条回答
  •  温柔的废话
    2020-12-04 16:50

    My solution (might be useful for someone looking here) is to do the comparison normal, with null values replaced not by 0, but the maximum value possible (e.g. Integer.MAX_VALUE). Returning 0 is not consistent, if you have values that are themselves 0. Here a correct example:

            public int compare(YourObject lhs, YourObject rhs) {
                Integer l = Integer.MAX_VALUE;
                Integer r = Integer.MAX_VALUE;
                if (lhs != null) {
                    l = lhs.giveMeSomeMeasure();
                }
                if (rhs != null) {
                    r = rhs.giveMeSomeMeasure();
                }
                return l.compareTo(r);
            }
    

    I just wanted to add that you don't necessary need the max value for integer. It depends of what your giveMeSomeMeasure() method can return. If for example you compare Celsius degrees for weather, you can set l and r to -300 or +300, depending where you want to set the null objects - to the head or the tail of the list.

提交回复
热议问题