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"
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.
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