按数值降序排列哈希图键 [英] Sort Hashmap keys by numerical value descending order
问题描述
如何通过数值对 HashMap
键进行排序?目前,在自然排序中,它看起来像这样:
1 10 13 2 26 29
我希望它看起来像这样:
29 26 13 10 2 1
有什么想法?
HashMap
无法排序。如果您需要排序的密钥,请查看 TreeMap的
。为了获得您想要的颠倒顺序,您必须提供自定义 Comparator
: class ReversedOrdering implements比较<整数> {
public int compare(Integer lhs,Integer rhs){
//比较反转
return rhs.compareTo(lhs);
}
}
编辑跨越 Collections.reverseOrder()
,它可以做你想做的事情:它给你一个 Comparator
,它颠倒实现对象的自然顺序可比
这节省了您自己编写比较器的麻烦。
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.
这篇关于按数值降序排列哈希图键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!