comparator with null values

前端 未结 9 1167
萌比男神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:51

    No, there is no cleaner way. Perhaps:

    • if the coordinates of both compared objects are null, return 0
    • if the coordinates of one of the objects are null, return -1 / 1 (depending on whether it's the first or the second argument)

    But more importantly - try to get rid of / fill in the missing coordinates, or, better: don't put addresses with missing coordinates in the list.

    Actually, not putting them in the list is the most logical behaviour. If you put them in the list, the result won't be actually ordered by distance.

    You may create another list, containing the addresses with missing coordinates, and make it clear to whoever needs that information (end-user, API user), that the first list only contains addresses with the needed data, while the second list contains addresses that lack required information.

提交回复
热议问题