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-1 2008-10-2 2008-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,
If another developper uses your method with a naive approach he would get 2008-10-01 which is not what was expected
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