Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to traverse Linked Hash Map in reverse? [duplicate]

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");
like image 700
Jagadeesh Avatar asked Jan 17 '12 10:01

Jagadeesh


People also ask

How do you reverse a linked HashMap?

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.

How do you reverse a traverse HashMap order?

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 does a linked hash map work?

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.


1 Answers

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());
}
like image 95
Óscar López Avatar answered Oct 17 '22 06:10

Óscar López