Java : Sorting a Map by Value

This page last changed on Apr 11, 2006 by Kees de Kooter

public class MapValueComparator implements Comparator {

    private Map map;
    private Boolean sortAscending;

    public MapValueComparator(Map map) {
        this(map, true);
    }
    
    public MapValueComparator(Map map, Boolean sortAscending) {
        this.map = map;
        this.sortAscending = sortAscending;
    }
    
    /**
     * @see java.util.Comparator#compare(T, T)
     */
    @SuppressWarnings("unchecked")
    public int compare(Object x, Object y) {
        
        Comparable object1 = (Comparable)map.get(x);
        Comparable object2 = (Comparable)map.get(y);
        
        int result = 0;
        
        if (sortAscending) {
            result = object1.compareTo(object2);
        } else {
            result = object2.compareTo(object1);
        }
       
        // If values are equal also compare keys
        if (result == 0) {
            if (sortAscending) {
                result = ((Comparable)x).compareTo((Comparable)y);
            } else {
                result = ((Comparable)y).compareTo((Comparable)x);
            }
        }
        
        return result;
    }

}

Example code for using this comparator

SortedMap sortedMap = new TreeMap(new MapValueComparator(map));
sortedMap.putAll(map);