首页 > 解决方案 > 如何对 HashMap 进行排序,值是整数。我想从高到低排序

问题描述

所以,我需要对“分数”哈希图进行排序。hashmap 布局是 HashMap<Player, Integer(这是我需要排序的分数>

如果你问为什么?这是因为我需要制作排行榜。

这是我的代码:

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

标签: javaarrayshashmap

解决方案


您可以使用Comparator.comparingInt以正确的顺序进行排序。Streams 可用于对新的排序和收集MapLinkedHashMap保留新的顺序。

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

推荐阅读