如何对 HashMap 进行排序,值是整数。我想从高到低排序

How to sort a HashMap, values are integers. I want to sort from highest to lowest

所以,我需要对“分数”哈希图进行排序。 hashmap布局是HashMap

如果你问为什么?因为我需要做一个排行榜。

这是我的代码:

public static Player[] sortPlayersByElo() {
        Map<String, Object> map = RankingConfig.get().getConfigurationSection("data").getValues(false);
        Map<Player, Integer> eloMap = new HashMap<>(); // Here is the map i need to sort.
        for (String s : map.keySet()) {
            Player player = Bukkit.getPlayer(s);
            eloMap.put(player, RankingConfig.get().getInt("data."+s+".elo"));
        }
        
        Player[] players = new Player[eloMap.size()];

        return players;
    }

您可以使用 Comparator.comparingInt 以正确的顺序排序。可以使用 Streams 将新的 Map 排序并收集到 LinkedHashMap 以保留新的顺序。

Map<Player, Integer> result = eloMap.entrySet().stream()
    .sorted(Comparator.comparingInt(Map.Entry::getValue))
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, 
         (a,b)->b, LinkedHashMap::new));