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");
Method 1: ( Using reverse() method) This method is used to reverse the elements or mappings order in the LinkedHashMap. Parameters: myList is the List provided to the Collections. reverse(myList) method. Returns: It does not return anything but modifies the list internally.
HashMap does not define any particular ordering of its element. Therefore the "reverse" order isn't defined either. For a TreeMap , you can use descendingMap() .
How LinkedHashMap Work Internally? Hash: All the input keys are converted into a hash which is a shorter form of the key so that the search and insertion are faster. Key: Since this class extends HashMap, the data is stored in the form of a key-value pair. Therefore, this parameter is the key to the data.
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With