I have a map storing the time series data in following format
HashMap<Date,Double> infiniteTimeSeries;
The variable infiniteTimeSeries can have data from 1AD to even 2100AD. When the user asks the values between Jan-1-1970 to Jan-1-1972, I need to pick the data corresponding to only the requested time range.
Is there an easy way to do this? Like a library. I am trying to avoid looping on the map , as the map can even have 100 years of data and iterating like 300000 elements for a short requested time range will affect the performance badly
Kindly please provide your valuable suggestions
答案 0 :(得分:6)
You could use a TreeMap
instead of a HashMap.
A TreeMap is sorted, by default, by the natural ordering of its keys. The java.util.Date
class defines a natural ordering by implementing Comparable<Date>
.
From the TreeMap, you can get a subset of the map over a range of keys, using TreeMap.subMap(). This version extends from fromKey
inclusive to toKey
exclusive. (A sibling allows other options.)
public SortedMap<K,V> subMap(K fromKey,
K toKey)
By the way, if you're working in Java 8, you might consider using the new Instant
class instead of the older Date class. Instant also implements Comparable.