If I have a data structure
Stock
{
String Symbol;
LinkedHashMap<Date,Double> DateForPrice;
}
I know in the LinkedHashMap, I can get the stock price of specific date without traversing the whole list.
However, if I want to iterate through the LinkedHashMap of DateForPrice starting from a specific date, are there any way to do it without traversing the whole list?
containsKey() method is used to check whether a particular key is being mapped into the LinkedHashMap or not. It takes the key element as a parameter and returns True if that element is mapped in the map.
LinkedHashMap
doesn’t offer a way to start iterating in the middle of its ordered view of the map’s data. Supposing your use case is really that you want all dates after some Date d
and to iterate those, then you should probably store your map as a TreeMap
. An important distinction here is that LinkedHashMap
’s ordering is the insertion-order, and our supposed use-case here is that you want the natural key-order. TreeMap
s maintain such a view, sorting the contents of the map by the map’s key.
TreeMap
s have the additional benefit of allowing you to create slices of the map based on the key, so you can call tailMap(K k)
, to return the map with all keys occurring after k
. In this case, you can call tailMap
with your starting point, d
.
e.g.:
TreeMap<Date, Double> dateForPrice;
// load up dateForPrice
Date start = // the point to start your iteration
for(Entry<Date, Double> entry : dateForPrice.tailMap(start).entrySet()){
// loop code
}
tailMap
method returns SortedMap
, which is not iterable. But it has entrySet
method returning Set
, which is subinterface of Iterable
.
Conveniently, if you want to keep storing your data in a LinkedHashMap
you can simply load up a TreeMap
with your current instance (with some performance tradeoff, of course):
TreeMap<Date, Double> dateSortedDateForPrice = new TreeMap<Date, Double>(dateForPrice);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With