Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How iteration last to first in HashMap?

Tags:

java

I have HashMAp

 items = new HashMap<String, String>();
        items.put("A", "1");
        items.put("B", "2");
        items.put("C", "3");

I need for each last to first.

"C", "3"
"B", "2"
"A", "1"
like image 769
Mediator Avatar asked Nov 21 '10 09:11

Mediator


1 Answers

You can use a NavigableMap (TreeMap is a NavigableMap), which is a SortedMap with navigation capabilities.

NavigableMap#descendingMap() returns a reverse order view (not a copy) of the mappings contained in this map.

Example :

NavigableMap<String, String> items = new TreeMap<String, String>();
items.put("B", "2");
items.put("A", "1");
items.put("C", "3");

for (Map.Entry<String, String> e : items.entrySet()) {
    System.out.println(e);
}
// gives
// A=1
// B=2
// C=3

for (Map.Entry<String, String> e : items.descendingMap().entrySet()) {
    System.out.println(e);
}

// gives
// C=3
// B=2
// A=1

Note : This answer is valid if you care about the natural ordering of the keys in your Map. If you care about the insertion ordering or the access ordering, then have a look at LinkedHashMap.

Note 2 : In your question, you used a HashMap. Please note that HashMap doesn't guarantee any order for its elements. Actually, it doesn't even guarantee the order will remain constant over time. See the first paragraph of HashMap's javadoc for further references.

like image 53
barjak Avatar answered Nov 04 '22 19:11

barjak