7

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?

Mark Elliot
  • 75,278
  • 22
  • 140
  • 160
Joe Liao
  • 71
  • 1
  • 3
  • 2
    Even if you can jump to a particular place, the iteration order of a `LinkedHashMap` will be the *insertion-order*, not the natural ordering of the keys; is that what you want? – Mark Elliot Jul 06 '11 at 02:48
  • Yes, that's what I want. The the stock price will be inserted in the order of date. – Joe Liao Jul 06 '11 at 02:52

2 Answers2

10

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);
Palec
  • 12,743
  • 8
  • 69
  • 138
Mark Elliot
  • 75,278
  • 22
  • 140
  • 160
  • in addition to tailMap() you can use subMap(Object fromKey, Object toKey), if you want to bound the new map you are creating. http://download.oracle.com/javase/1.4.2/docs/api/java/util/TreeMap.html – Kevin S Jul 06 '11 at 02:58
  • 1
    +1: Worth mentioning that what you really want is any NavigableMap e.g. TreeMap. – Peter Lawrey Jul 06 '11 at 05:28
0

I'd suggest to use TreeMap instead - it will be sorted by date and you can use tailMap to get the required portion

denis.solonenko
  • 11,645
  • 2
  • 28
  • 23