[英]Sort Hashmap keys by numerical value descending order
How can I sort HashMap
keys by their numerical value? 如何根据数值对
HashMap
键进行排序? 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. 无法对
HashMap
进行排序。 If you require sorted keys, take a look at the TreeMap
. 如果需要排序键,请查看
TreeMap
。 In order to get the reversed ordering you want, you would have to provide a custom Comparator
: 为了获得您想要的反向排序,您必须提供自定义
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
. 编辑我偶然发现了
Collections.reverseOrder()
,它可以满足您的需求:它为您提供了一个Comparator
,可以反转实现Comparable
的对象的自然顺序。 This saves you the hassle of writing a comparator yourself. 这样可以省去自己编写比较器的麻烦。
您可以使用TreeMap ,然后在其上调用descendingMap() ,它基本上返回一个具有键的反向排序的映射
Try below code it works fine and based on order flag it will sort ascending or descending. 尝试下面的代码,它工作正常,并根据订单标志,它将按升序或降序排序。
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
/**
* @author Rais.Alam
* @date Dec 12, 2012
*/
public class HelloWorld
{
public static void main(String[] args)
{
final boolean order = true;
try
{
Map<Integer, String> map = new TreeMap<Integer, String>(
new Comparator<Integer>()
{
@Override
public int compare(Integer first, Integer second)
{
if (order)
{
return second.compareTo(first);
}
else
{
return first.compareTo(second);
}
}
});
map.put(2, "v");
map.put(3, "h");
map.put(4, "e");
map.put(1, "a");
System.out.println(map);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
您可以将TreeMap与允许您指定Comparator的构造函数一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.