Java – the best way to find the date closest to the target in the date list?
I have a list of date objects and a target date I want to find the date closest to the target date in the list, but only the date before the target date
Example: October 1, 2008 October 2, 2008 October 4, 2008
The target date is October 3, 2008. I hope to get October 2, 2008
What is the best way?
Solution
The sietse de kaper solution assumes a reverse sort list, which is definitely not the most natural thing
The natural sort order in Java follows the ascending natural sort order (see collection.sort.) http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html#sort (Java. Util. List) document)
From your example,
target date = 2008-10-03 list = 2008-10-01 2008-10-02 2008-10-04
If another developer uses your method in a naive way, he will get 2008-10-01, which is not expected
>Don't make assumptions about the order of the list. > If you have performance reasons, please try to follow the most natural Convention (sorted in ascending order) > if you really have to follow another convention, you really should record 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 TreeSet's answer, but I think it may be a little slower because it is equivalent to sorting data and then finding it = > NLog (n) for sorting, and then the document implies that it is log (n) for access, so this will be NLog (n) log (n) vs n