如何实现支持重复键且可按键和值排序的Java Collection?
解决方案
完全可以实现,核心思路是使用**Map<Integer, List<Integer>>**结构:以玩家ID作为键,每个键对应一个存储该玩家所有得分的列表,之后对每个列表单独做降序排序即可。
具体实现步骤
- 选择Map实现类:如果不需要玩家ID按固定顺序输出,用
HashMap即可;如果需要玩家ID有序排列,改用TreeMap。 - 存储得分:每次给玩家添加得分时,先判断Map中是否已存在该玩家的键:
- 不存在则创建新的
ArrayList并放入Map; - 存在则直接向对应的List中追加得分。
- 不存在则创建新的
- 排序处理:所有得分添加完成后,遍历Map中的每个List,用
Collections.sort()结合反转比较器实现降序排序。
代码示例
import java.util.*; public class PlayerScoreManager { public static void main(String[] args) { // 初始化存储结构:键为玩家ID,值为该玩家的得分列表 Map<Integer, List<Integer>> playerScores = new HashMap<>(); // 录入玩家1的得分数据 addPlayerScore(playerScores, 1, 100); addPlayerScore(playerScores, 1, 200); addPlayerScore(playerScores, 1, 150); // 录入玩家2的得分数据 addPlayerScore(playerScores, 2, 140); addPlayerScore(playerScores, 2, 120); addPlayerScore(playerScores, 2, 210); // 对每个玩家的得分列表做降序排序 for (List<Integer> scores : playerScores.values()) { scores.sort(Collections.reverseOrder()); } // 按要求输出结果 for (Map.Entry<Integer, List<Integer>> entry : playerScores.entrySet()) { System.out.printf("%d = %s%n", entry.getKey(), entry.getValue()); } } private static void addPlayerScore(Map<Integer, List<Integer>> scoreMap, int playerId, int score) { // 若玩家ID不存在,自动创建新列表;存在则直接追加得分 scoreMap.computeIfAbsent(playerId, k -> new ArrayList<>()).add(score); } }
输出结果
1 = [200, 150, 100] 2 = [210, 140, 120]
补充说明
- 若需要在添加得分时就保持列表有序(避免最后统一排序),可以用
TreeSet代替ArrayList,但TreeSet会自动去重,若允许玩家有重复得分,仍建议用ArrayList+统一排序的方案。 - 你之前尝试的
TreeMap是按键排序的Map实现,本身不处理值的排序逻辑,因此需要结合列表的排序操作来满足需求。
内容的提问来源于stack exchange,提问作者Glandorf
相关产品推荐
相关产品推荐

