本文介绍了在日期列表中找到最接近目标的日期的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Date对象列表和一个目标日期。我想在列表中找到距离目标日期最近的日期,但仅在目标日期之前找到日期。



示例:
2008-10 -1
2008-10-2
2008-10-4



目标日期为2008-10-3,我想要2008-10-2



最好的方法是什么?

解决方案

Sietse de Kaper解决方案假定一个反向排序列表,绝对不是最自然的事情。



自然排序顺序java正在跟随自然排序顺序。 (请参阅Collection.sort 文档)



从您的示例中,

 
目标日期= 2008-10-03
列表= 2008-10-01 2008-10-02 2008-10-04

如果另一个开发者使用您的方法与天真的方法,他会得到2008-10-01这不是预期的



  • 不要对列表的排序做出假设。
  • 如果你出于表现原因试图遵循最自然的惯例(按升序排列)
  • 如果你真的要遵循另一个惯例,那么你真的应该记录下来。

     私人日期getDateNearest(列表&日期>日期,日期目标日期){
    日期returnDate = targetDate
    for(日期日期:日期){
    //如果当前迭代的日期是之前目标日期
    if(date.compareTo(targetDate) / /如果当前的迭代日期是after当前的返回日期
    if(date.compareTo(returnDate)> 0){
    returnDate = date;
    }
    }
    }
    return returnDate;
    }

    编辑 - 我也喜欢Treeset答案,但我认为可能会稍慢一些因为它等同于排序数据然后查找它们=> nlog(n)进行排序,然后文档意味着它是用于访问的log(n),因此将是nlog(n)+ log(n)vs n


    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.

    Example:2008-10-12008-10-22008-10-4

    With a target date of 2008-10-3, I want to get 2008-10-2

    What is the best way to do it?

    解决方案

    Sietse de Kaper solution assumes a reverse sorted list, definitely not the most natural thing to have around

    The natural sort order in java is following the ascending natural ordering. (see Collection.sort http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html#sort(java.util.List) documentation)

    From your example,

    target date = 2008-10-03
    list = 2008-10-01 2008-10-02 2008-10-04
    

    If another developper uses your method with a naive approach he would get 2008-10-01 which is not what was expected

  • Don't make assumptions as to the ordering of the list.
  • If you have to for performance reasons try to follow the most natural convention (sorted ascending)
  • If you really have to follow another convention you really should document the hell out of it.

    private Date getDateNearest(List<Date> dates, Date targetDate){
      Date returnDate = targetDate
      for (Date date : dates) {
        // if the current iteration'sdate is "before" the target date
        if (date.compareTo(targetDate) <= 0) {
          // if the current iteration's date is "after" the current return date
          if (date.compareTo(returnDate) > 0){
            returnDate=date;
          }
        }
      }
      return returnDate;
    }
    

    edit - I also like the Treeset answer but I think it might be slightly slower as it is equivalent to sorting the data then looking it up => nlog(n) for sorting and then the documentation implies it is log(n) for access so that would be nlog(n)+log(n) vs n

    这篇关于在日期列表中找到最接近目标的日期的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

  • 09-06 05:42