How do you sort a Map by Value?

Given the following HashMap
1
2
3
4
5
Map<String, Integer> voteMap = new HashMap<String, Integer>();
voteMap.put("Doc Brown", 12);
voteMap.put("Marty McFly", 88);
voteMap.put("Biff Tannen", 5);
voteMap.put("George McFly", 0);



One way to do this is to store the Entries of the Map in an ArrayList.

Store Entries in ArrayList
1
List<Entry<String, Integer>> entries = new ArrayList<Entry<String, Integer>>(voteMap.entrySet());



The task becomes easy at this point and you can simply use the built-in Collections.sort method to sort the ArrayList providing a Comparator for the value comparison.

Sort the ArrayList
1
2
3
4
5
6
Collections.sort(entries, new Comparator<Entry<String, Integer>>() {
    @Override
    public int compare(Entry<String, Integer> a, Entry<String, Integer> b) {
        return a.getValue() - b.getValue();
    }
});



This will have the following output

Console Output
George McFly=0
Biff Tannen=5
Doc Brown=12
Marty McFly=88



You have now sorted the list in Ascending order, but what if you want Descending order? The comparator determines the order so simply switching the a <-> b comparison will flip the order.

Sort the ArrayList
1
2
3
4
5
6
Collections.sort(entries, new Comparator<Entry<String, Integer>>() {
    @Override
    public int compare(Entry<String, Integer> a, Entry<String, Integer> b) {
        return b.getValue() - a.getValue();
    }
});



This results in the following output

Console Output
Marty McFly=88
Doc Brown=12
Biff Tannen=5
George McFly=0