Find nearest date among several dates to a given date

前端 未结 5 1425
一个人的身影
一个人的身影 2020-12-10 14:58

I have a list of dates and a current date. How can I find the date which is nearest to the current date?

5条回答
  •  囚心锁ツ
    2020-12-10 14:59

    If the list is sorted, then you can use Collections.binarySearch() to find the place where the given date would be sorted into the list - the closest one is either right after or right before that index.

    For very large lists, this is much faster than the other solutions, but of course it does require the list to be sorted. If you're going to do such a query multiple times, it would be worth it (performance-wise) to sort the list first.

提交回复
热议问题