You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除HashMap<Integer, ArrayList<Integer>>中的重复列表值?

移除HashMap中重复的ArrayList值条目

要删除HashMap中值(ArrayList)重复的条目,核心是利用ArrayList的equals方法会判断列表内容是否一致的特性,结合集合跟踪已出现的列表,具体有两种常用实现方式:

方法一:迭代遍历删除(避免并发修改异常)

通过迭代器遍历HashMap条目,用HashSet记录已见过的列表,遇到重复值时直接删除对应条目:

// 辅助集合,记录已出现的列表内容
Set<ArrayList<Integer>> seenLists = new HashSet<>();
Iterator<Map.Entry<Integer, ArrayList<Integer>>> iterator = myList.entrySet().iterator();

while (iterator.hasNext()) {
    Map.Entry<Integer, ArrayList<Integer>> entry = iterator.next();
    ArrayList<Integer> currentList = entry.getValue();
    // HashSet.add()返回false表示元素已存在,此时删除当前条目
    if (!seenLists.add(currentList)) {
        iterator.remove();
    }
}

如果你的ArrayList后续可能被修改,建议存入Set时创建列表副本,避免原列表改动影响去重结果:

Set<List<Integer>> seenLists = new HashSet<>();
Iterator<Map.Entry<Integer, ArrayList<Integer>>> iterator = myList.entrySet().iterator();

while (iterator.hasNext()) {
    Map.Entry<Integer, ArrayList<Integer>> entry = iterator.next();
    ArrayList<Integer> currentList = entry.getValue();
    List<Integer> listCopy = new ArrayList<>(currentList);
    if (!seenLists.add(listCopy)) {
        iterator.remove();
    }
}

方法二:用Stream API创建新的HashMap

适合Java 8及以上版本,通过Stream收集器直接过滤重复值,保留第一个出现的条目:

HashMap<Integer, ArrayList<Integer>> uniqueMap = myList.entrySet()
    .stream()
    // 按列表值分组,重复时保留第一个出现的条目
    .collect(Collectors.toMap(
        Map.Entry::getValue,
        entry -> entry,
        (existing, newEntry) -> existing, // 冲突时保留原有条目
        HashMap::new
    ))
    .values()
    .stream()
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

执行完上述任意一种方法后,原HashMap(或新的uniqueMap)中只会保留值不重复的条目,比如你的示例中会移除键2对应的条目,最终结果为:

0 [1,3]
1 [0,3]
3 [1,4]
4 [2,4]

内容的提问来源于stack exchange,提问作者Karlz-Bandz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 03:30:46