How to traverse Linked Hash Map in reverse?

Jagadeesh picture Jagadeesh · Jan 17, 2012 · Viewed 17k times · Source

Possible Duplicate:
Iterating through a LinkedHashMap in reverse order

How to traverse Linked Hash Map in a reverse order? Is there any predefined method in map to do that?

I'm creating it as follows:

LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer,String>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");

Answer

&#211;scar L&#243;pez picture Óscar López · Jan 17, 2012

Try this, it will print the keys in reverse insertion order:

ListIterator<Integer> iter =
    new ArrayList<>(map.keySet()).listIterator(map.size());

while (iter.hasPrevious()) {
    Integer key = iter.previous();
    System.out.println(key);
}

You can also iterate by the reverse insertion order of entries:

ListIterator<Map.Entry<Integer, String>> iter =
    new ArrayList<>(map.entrySet()).listIterator(map.size());

while (iter.hasPrevious()) {
    Map.Entry<Integer, String> entry = iter.previous();
    System.out.println(entry.getKey() + ":" + entry.getValue());
}