Sorting the Map in descending order based on the value [duplicate]

Since you can have duplicate values you shouldn’t be using a Set at all. Change to a List and sort it instead. Your entriesSortedByValues would look something like this:

static <K,V extends Comparable<? super V>> 
            List<Entry<K, V>> entriesSortedByValues(Map<K,V> map) {

    List<Entry<K,V>> sortedEntries = new ArrayList<Entry<K,V>>(map.entrySet());

    Collections.sort(sortedEntries, 
            new Comparator<Entry<K,V>>() {
                @Override
                public int compare(Entry<K,V> e1, Entry<K,V> e2) {
                    return e2.getValue().compareTo(e1.getValue());
                }
            }
    );

    return sortedEntries;
}

Note: in your example output the values is descending. If you want them ascending, use e1.getValue().compareTo(e2.getValue()) instead.


Example:

public static void main(String args[]) {

    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("A", 34);
    map.put("B", 25);
    map.put("C", 50);
    map.put("D", 50); // "duplicate" value

    System.out.println(entriesSortedByValues(map));
}

Output:

[D=50, C=50, A=34, B=25]

Leave a Comment