I have this HashMap
that I need to print out in ascending order according to the values contained in it (not the keys).
But the order when I print it out is seemingly random.
What's the best way to print it out in ascending value order?
Map<String, String> codes = new HashMap<String, String>(); codes.put("A1", "Aania"); codes.put("X1", "Abatha"); codes.put("C1", "Acathan"); codes.put("S1", "Adreenas");
In other words, the example above should print out as this:
A1, Aania X1, Abatha C1, Acathan S1, Adreenas
In your case, you want to extract the collection provided by the HashMap. entrySet() method, using a Comparator that orders the Map<K,V>. Entry objects by value and then by key. The simple way to print the sorted entries is to use a loop.
If we need to sort the HashMap by values, we should create a Comparator. It compares two elements based on the values. After that get the Set of elements from the Map and convert Set into the List. Use the Collections.
No, the order is not preserved in case of HashMap (if you want sorted implementation.) In case you want keys to be sorted, you can use TreeMap.
You aren't going to be able to do this from the HashMap class alone.
I would take the Map<String, String> codes
, construct a reverse map of TreeMap<String, String> reversedMap
where you map the values of the codes
Map to the keys (this would require your original Map to have a one-to-one mapping from key-to-value). Since the TreeMap provides Iterators which returns entries in ascending key order, this will give you the value/key combination of the first map in the order (sorted by values) you desire.
Map<String, String> reversedMap = new TreeMap<String, String>(codes); //then you just access the reversedMap however you like... for (Map.Entry entry : reversedMap.entrySet()) { System.out.println(entry.getKey() + ", " + entry.getValue()); }
There are several collections libraries (commons-collections, Google Collections, etc) which have similar bidirectional Map implementations.
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