简体   繁体   English

如何按值降序排列 HashMap 并按字母顺序排列?

[英]How do I sort a HashMap in descending order by Value and alphabetically by Key?

So I have this HashMap所以我有这个 HashMap

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

And the contents of it:以及它的内容:

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

And I want the output to be where Apple precedes Kiwi alphabetically:我希望 output 按字母顺序排列在 Apple 之前 Kiwi 的位置:

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

Is it possible to sort this?可以排序吗?

Your question has some ambiguity because the result you have mentioned, are not alphabetically sorted by key and ordering by value makes no sense.您的问题有些模棱两可,因为您提到的结果不是按字母顺序按键排序的,按值排序没有意义。

However, seems like you want to order by only the first letter of the key (so Apple and Appricots become a tie) and if there's a tie, order by the value.但是,似乎您只想按键的第一个字母排序(因此 Apple 和 Appricots 成为平局),如果有平局,则按价值排序。 Assuming this, I propose the following solution:假设这一点,我提出以下解决方案:

    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);

Here we use a custom comparator to order the entries of the map.在这里,我们使用自定义比较器对 map 的条目进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM