简体   繁体   中英

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

So I have this 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:

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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