首页 > 解决方案 > 如何获得 HashMap 中的 3 个最高值?

问题描述

我有一个哈希图,如下所示:

    HashMap<String, Integer> hm = new HashMap<String, Integer>;
    hm.put("a", 1);
    hm.put("b", 12);
    hm.put("c", 53);
    hm.put("d", 2);
    hm.put("e", 17);
    hm.put("f", 8);
    hm.put("g", 8);

我将如何获得具有 3 个最高值的键?所以它会返回:

    "c", "e", "b"

谢谢。

标签: javasortinghashmapentryset

解决方案


我的解决方案,按值排序并获得前 3 名并返回键列表。

List<String> keys = hm.entrySet().stream().sorted(Map.Entry.<String, Integer>comparingByValue().reversed()).limit(3).map(Map.Entry::getKey).collect(Collectors.toList());

希望能帮助到你


推荐阅读