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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With