Best way to find date nearest to target in a list of dates?

后端 未结 6 520
萌比男神i
萌比男神i 2020-12-10 18:03

I have a list of Date objects, and a target Date. I want to find the date in the list that\'s nearest to the target date, but only dates that are before the target date.

6条回答
  •  死守一世寂寞
    2020-12-10 18:19

    private Date getDateNearest(List dates, Date targetDate){
        return new TreeSet(dates).lower(targetDate);
    }
    

    Doesn't require a pre-sorted list, TreeSort fixes that. It'll return null if it can't find one though, so you will have to modify it if that's a problem. Not sure of the efficency either :P

提交回复
热议问题