Sort Hashmap keys by numerical value descending order

17,523

Solution 1

A HashMap cannot be sorted. If you require sorted keys, take a look at the TreeMap. In order to get the reversed ordering you want, you would have to provide a custom Comparator:

class ReversedOrdering implements Comparator<Integer> {
    public int compare(Integer lhs, Integer rhs) {
        // compare reversed
        return rhs.compareTo(lhs);
    }
}

Edit I just stumbled across Collections.reverseOrder() which does just what you want: It gives you a Comparator that reverses the natural ordering of objects that implement Comparable. This saves you the hassle of writing a comparator yourself.

Solution 2

You can use a TreeMap and then call descendingMap() on it which basically returns a map with the reverse ordering of the keys

Share:
17,523
Maurice
Author by

Maurice

Updated on June 05, 2022

Comments

  • Maurice
    Maurice almost 2 years

    How can I sort HashMap keys by their numerical value? Currently, in the natural ordering it looks like this:

    1 10 13 2 26 29
    

    I want it to look like this:

    29 26 13 10 2 1
    

    Any ideas?

  • Maurice
    Maurice over 12 years
    I realised my key was not numerical anymore. Thanks for the info though!
  • Björn Pollex
    Björn Pollex over 12 years
    @Maurice: I have added a simpler solution to get the reverse of a natural ordering (the type of the keys does not matter: if the implement Comparable, you can reverse the ordering this way).