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

后端 未结 6 524
萌比男神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:32

    I currently use the following method, but I'm not sure it's the most effective one, because this assumes an already sorted list, and (potentially) iterates over every single date in the list.

    private Date getDateNearest(List dates, Date targetDate){
      for (Date date : dates) {
        if (date.compareTo(targetDate) <= 0) return date;
      }
    
      return targetDate;
    }
    

提交回复
热议问题