如何按整数值对哈希映射进行排序,我找到的答案之一是
here
由Evgeniy Dorofeev撰写,他的回答是这样的
HashMap<String,Integer> map = new HashMap<String,Integer>();
map.put("a",4);
map.put("c",6);
map.put("b",2);
Object[] a = map.entrySet().toArray();
Arrays.sort(a,new Comparator() {
public int compare(Object o1,Object o2) {
return ((Map.Entry<String,Integer>) o2).getValue().compareto(
((Map.Entry<String,Integer>) o1).getValue());
}
});
for (Object e : a) {
System.out.println(((Map.Entry<String,Integer>) e).getKey() + " : "
+ ((Map.Entry<String,Integer>) e).getValue());
}
产量
c : 6 a : 4 b : 2
我的问题是如何成为描述?如果我想对HashMap Asc进行排序我该怎么做?
最后一个问题是:如何在排序后获得第一个元素?
解决方法
对于反向排序开关o2和o1.要获取第一个元素,只需访问索引0处的数组:
Map<String,Integer> map = new HashMap<>();
map.put("a",4);
map.put("c",6);
map.put("b",2);
Object[] a = map.entrySet().toArray();
Arrays.sort(a,new Comparator() {
public int compare(Object o1,Object o2) {
return ((Map.Entry<String,Integer>) o1).getValue().compareto(
((Map.Entry<String,Integer>) o2).getValue());
}
});
for (Object e : a) {
System.out.println(((Map.Entry<String,Integer>) e).getKey() + " : "
+ ((Map.Entry<String,Integer>) e).getValue());
}
System.out.println("first element is " + ((Map.Entry<String,Integer>) a[0]).getKey() + " : "
+ ((Map.Entry<String,Integer>) a[0]).getValue());
哪个打印
b : 2
a : 4
c : 6
first element is b : 2
如果您有权访问lambda表达式,则可以使用以下方法简化排序:
Arrays.sort(a,(o1,o2) -> ((Map.Entry<String,Integer>) o1).getValue().compareto(((Map.Entry<String,Integer>) o2).getValue()));