Sorting a HashMap by Value in Java

Sometimes Java drives you nuts… you want to save word bigrams and their frequencies as an example. A HashMap<String, Integer> is very convenient. Now we want to sort it by value. And the fun begins! Of course we do not want to lose the connection between keys and values, so we cannot just use Collections.sort(map.keySet()) (or the same for values). Also using a TreeMap with a custom-wrote Comparator for our pairs does not work, because there you cannot have identical values (another fun fact).

Here is a generic method that sorts the given HashMap by value. V can be anything as long as it can be compared with itself.

public static <K, V extends Comparable<V>> List<Entry<K, V>> sortHashMapByValue (HashMap<K, V> theMap) {
   List<Entry<K, V>> resultList = new ArrayList<Entry<K, V>>(theMap.entrySet());
   Collections.sort(resultList,
          new Comparator<Entry<K, V>>() {
            @Override
            public int compare(Entry<K, V> o1, Entry<K, V> o2) {
               return o1.getValue().compareTo(o2.getValue());
            }
       });
   return resultList;
This entry was posted in Programming and tagged , , , , by swk. Bookmark the permalink.

About swk

I am a software developr, data scientist, computational linguist, teacher of computer science and above all a huge fan of LaTeX. I use LaTeX for everything, including things you never wanted to do with LaTeX. My latest love is lilypond, aka LaTeX for music. I'll post at irregular intervals about cool stuff, stupid hacks and annoying settings I want to remember for the future.