Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Hashmap keys by numerical value descending order

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?

like image 619
Maurice Avatar asked Dec 05 '22 20:12

Maurice


1 Answers

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.

like image 100
Björn Pollex Avatar answered Dec 14 '22 23:12

Björn Pollex