javahashmaplinkedhashmap

Iterating through a LinkedHashMap in reverse order


I have a LinkedHashMap:

LinkedHashMap<String, RecordItemElement>

that I need to iterate through from a given key's position, backwards. So if I was given the 10th item's key, I'd need iterate backwards through the hashmap 9, 8, 7 etc.


Solution

  • You don't have to iterate through it. But it would be handy to pull the keys off and store it in a list. Thats the only way you can do indexOf() type operations.

    List<String> keyList = new ArrayList<String>(map.keySet());
    // Given 10th element's key
    String key = "aKey";
    int idx = keyList.indexOf(key);
    for ( int i = idx ; i >= 0 ; i-- ) 
     System.out.println(map.get(keyList.get(i)));