Sometimes we want to sort a Map by its values, as opposed to its keys. Occasionally this can be done by reversing the Map as in the example here, but more likely you need to sort a List of the entries. Why? Because values could be duplicated, in which case entries would be lost on reversal, since a Map can't contain duplicate keys. Here is a way of sorting, The code is HERE

import java.util.*;

public class MapValueSort {
    public static void main(String[] args) {
        Map<String, String> m = new HashMap<String, String>();
        m.put("zero", "0");
        m.put("nil", "0");
        m.put("one", "1");

        List<Map.Entry<String, String>> entries = MapValueSort.sortByValue(m);

    public static <K, V extends Comparable> List<Map.Entry<K, V>> sortByValue(
        Map<K, V> map) {
        List<Map.Entry<K, V>> entries = new ArrayList<Map.Entry<K, V>>(map.size());
            new Comparator<Map.Entry<K, V>>() {
                public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) {
                    return e1.getValue().compareTo(e2.getValue());

        return entries;