如何按值降序和键字母顺序对hashmap排序?

mbjcgjjk  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(396)

所以我有这个哈希图

HashMap<String, Integer> hm = new HashMap <String, Integer>();

以及它的内容:

Key: "Apricots" Value: 3
Key: "Kiwi"  Value: 2
Key: "Apple"  Value: 2
Key: "Orange"  Value: 1

我希望输出的结果是苹果在猕猴桃之前的字母顺序:

Key: "Apricots" Value: 3
Key: "Apple"    Value: 2
Key: "Kiwi"   Value: 2
Key: "Orange"  Value: 1

能把这个分类吗?

6rvt4ljy

6rvt4ljy1#

你的问题有些模棱两可,因为你提到的结果不是按字母键排序的,按值排序是没有意义的。
但是,似乎您只想按键的第一个字母排序(这样apple和appricots就成了平局),如果有平局,就按值排序。假设如此,我提出以下解决方案:

Map<String, Integer> map = new HashMap<>();
    map.put("Apricots", 3);
    map.put("Kiwi", 2);
    map.put("Apple", 1);
    map.put("Orange", 1);

    List<Map.Entry<String, Integer>> list = map.entrySet().stream()
            .sorted((e1, e2) -> {
                // Compare only the first 2 letters
                int res = e1.getKey().substring(0, 1).compareTo(e2.getKey().substring(0, 1));
                if (res == 0) {
                    // If its a tie, compare values DESC
                    return e2.getValue().compareTo(e1.getValue());
                }

                return res;
            })
            .collect(Collectors.toList());

    System.out.println(list);

这里我们使用一个定制的比较器来排序Map的条目。

相关问题