java - 如何对 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;
}
解决方案
您可以使用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));
推荐阅读
- excel - 更新每个循环变量
- javascript - 从 Rechart 图中删除参考虚线
- node.js - Nginx 反向代理到 nodeJS。Vuejs 如何适应?
- python - 在熊猫列中第二次出现后获取前 4 个字符之前的所有子字符串
- javascript - React 正在渲染 [object object] 而不是 UI 中的 JSX
- excel - 当一个用户窗体被卸载时,为什么关联的对象没有设置为空?
- ios - 子视图未使用自动布局与 centerX 对齐
- ios - 使用 Facebook iOS SDK 将链接发送给直接用户
- database - 备份带有 cassandra 的 where 子句结果的选择,以便稍后恢复
- python - 打印取决于给定的参数数量