如何通过整数值对
我的问题是如何使排序变为 降序 ?? 如果我想对
hashmap
进行排序,我找到的其中一种答案在这里,作者是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
进行 升序 排序,该怎么做?同时,如何在排序后取得第一个元素呢?
compare
方法中通过将o2
和o1
交换来反转顺序-获取第一个元素只需使用a [0]
,然后使用与for循环相同的逻辑来获取值和键! - luk2302