按照整数值降序排序哈希映射表

7
如何通过整数值对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 进行 升序 排序,该怎么做?同时,如何在排序后取得第一个元素呢?

2
你可以在compare方法中通过将o2o1交换来反转顺序-获取第一个元素只需使用a [0],然后使用与for循环相同的逻辑来获取值和键! - luk2302
1
可能是如何在Java中按值对Map<Key,Value>进行排序?的重复问题。 - Ramesh-X
不,我的问题是关于用户编写的代码,正如我在问题中所指定的那样 :) - Abeer zaroor
3个回答

7

要逆序排列,请将o2o1交换位置。要获取第一个元素,只需访问索引为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
第一个元素是 b : 2

如果您可以访问 lambda 表达式,可以使用它们简化排序过程:

Arrays.sort(a, (o1, o2) -> 
   ((Map.Entry<String, Integer>) o1).getValue().compareTo(((Map.Entry<String, Integer>) o2).getValue()));

3

在Java 8中,您可以进行以下操作:

System.out.println(map.entrySet().stream().sorted((o1, o2) -> {
        return o2.getValue().compareTo(o1.getValue());
    }).findFirst());//would return entry boxed into optional which you can unbox.

谢谢你的回答 :) - Abeer zaroor
没问题。它简洁易读。您不必进行多个对象到条目的转换和反向转换。 - SMA

2
首先,回答你的问题:只需反转compare方法的结果即可将升序改为降序。
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) {
        // just reverse the result of the comparison 
        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());
}

但是,如果您需要使用已排序的Map,我建议您使用一个TreeMap实例,它可以自己处理排序。


非常感谢 @Orlangure。 - Abeer zaroor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接