Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 575
Joe Liao Avatar asked Jul 06 '11 02:07

Joe Liao


People also ask

How do I search for a key in LinkedHashMap?

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.


1 Answers

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. TreeMaps maintain such a view, sorting the contents of the map by the map’s key.

TreeMaps 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);
like image 99
Mark Elliot Avatar answered Sep 22 '22 17:09

Mark Elliot