File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Date ranges in collections Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Date ranges in collections" Watch "Date ranges in collections" New topic

Date ranges in collections

Will Myers
Ranch Hand

Joined: Aug 05, 2009
Posts: 370

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: 195
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: 195
I wrote a simple test...

The DateHolder:

A generator for some periods

And finally the main-class which checks some dates:

I agree. Here's the link:
subject: Date ranges in collections
It's not a secret anymore!