Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How print out the contents of a HashMap<String, String> in ascending order based on its values?

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 
like image 949
Carlsberg Avatar asked Aug 31 '10 00:08

Carlsberg


People also ask

How do I print a HashMap in a sorted order?

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.

How do you sort a given HashMap on the basis of values?

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.

Does HashMap store values in order?

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.


1 Answers

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.

like image 176
matt b Avatar answered Oct 07 '22 17:10

matt b