views:

65

answers:

4

What I need is something like Hashtable which I will fill with prices that were actual at desired days.

For example: I will put two prices: January 1st: 100USD, March 5th: 89USD.

If I search my hashtable for price: hashtable.get(February 14th) I need it to give me back actual price which was entered at Jan. 1st because this is the last actual price. Normal hashtable implementation won't give me back anything, since there is nothing put on that dat.

I need to see if there is such implementation which can find quickly object based on range of dates.

+5  A: 

Off the top of my head, there are a couple ways, but I would use a TreeMap<Date> (or Calendar, etc).

When you need to pull out a Date date, try the following:

  1. Attempt to get(date)
  2. If the result is null, then the result is in headMap(date).lastKey()

One of those will work. Of course, check the size of headMap(date) first because lastKey() will throw an Exception if it is empty.

Phil
+1 This is the right way to do it. Can be improved a little with Java 6, using TreeMap.floorEntry(date)
Eyal Schneider
Thanks for the tip on floorEntry!
Phil
+1 was not aware of this feature of `TreeMap`!
Vivin Paliath
A: 

You could use a DatePrice object that contains both and keep those in a list or array sorte by date, then use binary search (available in the Collections and Arrays classes) to find the nearest date.

This would be significantly more memory-effective than using TreeMap, and it doesn't look like you'll want to insert or remove data randomly (which would lead to bad performance with a array).

Michael Borgwardt
no.. just need to fill cache of prices from database so I don't have to hit db any time I need a price for a product at some random date. Prices won't be changing on a daily basis, maybe once in a month, what is crucial is to find quickly price that was lets say 10 years ago at some date precisely.
ante.sabo
A: 

Create a Tree Map with Date,String. If some one calls for a date then convert the string to date and call map.get(date), if you find then take the previous key than the current element.

Phani
A: 

You have all your tools already at hand. Consider a TreeMap. Then you can create a headmap, that contains only the portion of the map that is strictly lower that a given value. Implementation example:

TreeMap<Date,Double> values = new TreeMap<Date,Double>();
...fill in stuff...
Date searchDate = ...anydate...
// Needed due to the strictly less contraint:
Date mapContraintDate = new Date(searchDate.getTime()+1); 
Double searchedValue = values.get(values.headMap(mapContraintData).lastKey);

This is efficient, because the headMap is not create by copying the original map, but returns only a view.

Daniel