How to traverse Linked Hash Map in reverse?
List<Entry<Integer,String>> list = new ArrayList<>(map.entrySet());
for( int i = list.size() -1; i >= 0 ; i --){
Entry<Integer,String> entry = list.get(i);
}
Not really pretty and at the cost of a copy of the entry set, which if your map has a significant number of entries might be a problem.
The excellant Guava library have a [List.reverse(List<>)][2]
that would allow you to use the Java 5 for each style loop rather than the indexed loop:
//using guava
for( Entry entry : Lists.reverse(list) ){
// much nicer
}
Guava RULES:
List<Object> reverseList = Lists.reverse(
Lists.newArrayList(map.keySet()));
Lists.reverse
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());
}