How can I iterate starting at a particular key in a LinkedHashMap?
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?
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);
I'd suggest to use TreeMap
instead - it will be sorted by date and you can use tailMap
to get the required portion
精彩评论