Java中如何合并同keyResult的List并去除重复值?
解决HeuristicResult实例合并与去重问题
看来你卡在了HeuristicResult实例的合并和去重上——你只处理了单个实例里moves的重复元素,但没解决相同keyResult实例重复出现的问题,对吧?核心问题在于你没有先按keyResult对实例进行分组,而是直接在遍历中修改,导致最终列表里仍有重复的HeuristicResult对象。下面是完整的解决方案:
核心思路
- 按keyResult分组:用
Map<Integer, Set<Integer>>来存储每个keyResult对应的去重后moves集合(Set天然具备去重特性)。 - 遍历合并:遍历原始列表,将每个实例的moves合并到对应key的Set中,自动完成去重。
- 转换为结果列表:把Map中的键值对转换回
HeuristicResult实例,得到最终的合并去重列表。
代码实现
假设你的HeuristicResult类定义如下:
public class HeuristicResult { private int keyResult; private List<Integer> moves; // 构造器、Getter和Setter public HeuristicResult(int keyResult, List<Integer> moves) { this.keyResult = keyResult; this.moves = moves; } public int getKeyResult() { return keyResult; } public List<Integer> getMoves() { return moves; } public void setMoves(List<Integer> moves) { this.moves = moves; } }
合并去重的方法:
import java.util.*; public class HeuristicResultMerger { public List<HeuristicResult> mergeAndDeduplicate(List<HeuristicResult> originalResults) { // 用Map按keyResult分组,存储去重后的moves集合 Map<Integer, Set<Integer>> keyToUniqueMoves = new HashMap<>(); for (HeuristicResult result : originalResults) { int key = result.getKeyResult(); // 若key不存在则创建新的HashSet,否则获取已存在的Set Set<Integer> uniqueMoves = keyToUniqueMoves.computeIfAbsent(key, k -> new HashSet<>()); // 批量添加当前moves到Set,自动去重 uniqueMoves.addAll(result.getMoves()); } // 将Map转换为HeuristicResult列表 List<HeuristicResult> mergedResults = new ArrayList<>(); for (Map.Entry<Integer, Set<Integer>> entry : keyToUniqueMoves.entrySet()) { // 把Set转回List,若需要保留元素插入顺序,可改用LinkedHashSet List<Integer> deduplicatedMoves = new ArrayList<>(entry.getValue()); mergedResults.add(new HeuristicResult(entry.getKey(), deduplicatedMoves)); } return mergedResults; } }
关键说明
- 为什么用Map分组:Map能确保每个
keyResult只对应一个集合,从根源上避免了重复的HeuristicResult实例。 - Set去重的优势:HashSet会自动忽略重复元素,无需手动判断;如果需要保留moves的原始顺序,可以把
HashSet换成LinkedHashSet。 - 避免原列表干扰:这个方法不会修改原始列表的实例,而是生成全新的合并后列表,逻辑更清晰也更安全。
如果你之前的代码是在遍历原列表时修改实例但没移除重复项,那最终列表里自然会有多个相同keyResult的实例——而用Map分组的方式能彻底解决这个问题。
内容的提问来源于stack exchange,提问作者alex_z
相关产品推荐
相关产品推荐

