如何hashmap按整数值排序a ,我找到的答案之一就在这里
由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());
}
Run Code Online (Sandbox Code Playgroud)
产量
c : 6
a : 4
b : 2
Run Code Online (Sandbox Code Playgroud)
我的问题是如何成为描述?如果我想对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());
Run Code Online (Sandbox Code Playgroud)
哪个打印
b:2
a:4
c:6
第一个元素是b:2
如果您有权访问lambda表达式,则可以使用以下方法简化排序:
Arrays.sort(a, (o1, o2) ->
((Map.Entry<String, Integer>) o1).getValue().compareTo(((Map.Entry<String, Integer>) o2).getValue()));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1571 次 |
| 最近记录: |