Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Date ranges in collections

 
Will Myers
Ranch Hand
Posts: 381
Java jQuery Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 197
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 197
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wrote a simple test...

The DateHolder:


A generator for some periods


And finally the main-class which checks some dates:

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic