| Author |
Date ranges in collections
|
Will Myers
Ranch Hand
Joined: Aug 05, 2009
Posts: 285
|
|
|
I have a use case where I want to store date ranges in a collection (an object with a start and end date) and find the relevant one that covers a passed in date. I can obviously do this by having a method on the DateRange object to determine if the passed in date falls in this range and iterate through the collection calling this method on each object but this doesn't seem very efficient. Is there a better way to do this? The collection could potentially be huge....
|
 |
Christian Dillinger
Ranch Hand
Joined: Jul 20, 2009
Posts: 172
|
|
I'd create a class that holds fromDate and toDate (let's call it DateHolder) which implements Comparable. In comparable I'd only compare fromDate or toDate. Then you put your objects into a TreeSet.
For each Date you have to check I'd create a DateHolder instance and fill only that field you used in your impl of Comparable.
Now query your TreeSet either by headSet or tailSet (depending on your imp of comparable).
Explanation: If a day is a certain period it has to be before the end of that period. So you only have to check items where toDate is greater than your current day. headSet or tailSet gives you those periods as a SortedSet. Iterate over it and check if your date is after the beginning of the period.
|
 |
Christian Dillinger
Ranch Hand
Joined: Jul 20, 2009
Posts: 172
|
|
I wrote a simple test...
The DateHolder:
A generator for some periods
And finally the main-class which checks some dates:
|
 |
 |
|
|
subject: Date ranges in collections
|
|
|