如何移除HashMap中作为值存储的重复List集合
解决HashMap中List值重复的问题
嘿,这个场景我之前处理过!你的问题核心是:HashMap只会保证键的唯一性,完全不管值是否重复,所以即使两个List内容一模一样,只要键不同,都会被存进去。咱们要做的就是手动过滤掉值重复的键值对,只保留每个唯一List对应的一个条目。
思路解析
- 用一个
Set来记录已经出现过的List——因为Set的特性就是自动去重,而ArrayList的equals()和hashCode()方法是基于元素内容实现的,所以内容完全相同的List会被Set视为同一个元素。 - 遍历HashMap的条目,用Set来判断当前List是否已经出现过:如果没出现过就保留,已经出现过就移除对应的键值对。
修正后的完整代码
import java.util.*; public class Test { public static void main(String args[]) { Map<String, List<Integer>> sample = new HashMap<String, List<Integer>>(); List<Integer> first = new ArrayList<>(); first.add(1); first.add(2); first.add(3); List<Integer> second = new ArrayList<>(); second.add(4); second.add(5); second.add(6); List<Integer> third = new ArrayList<>(); third.add(1); third.add(2); third.add(3); sample.put("first", first); sample.put("second", second); sample.put("third", third); System.out.println("原Map大小:" + sample.size()); // 输出3 // 开始移除重复的List值 Set<List<Integer>> seenLists = new HashSet<>(); // 使用迭代器遍历,避免并发修改异常 Iterator<Map.Entry<String, List<Integer>>> iterator = sample.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, List<Integer>> entry = iterator.next(); List<Integer> currentList = entry.getValue(); // 如果add返回false,说明这个List已经存在过 if (!seenLists.add(currentList)) { iterator.remove(); } } System.out.println("去重后Map大小:" + sample.size()); // 输出2 // 打印验证结果 sample.forEach((key, value) -> System.out.println(key + ": " + value)); } }
关键细节说明
- 为什么用迭代器?:如果直接用for-each遍历Map并修改(比如remove),会抛出
ConcurrentModificationException,迭代器是安全修改集合的方式。 - 保留顺序的可选方案:如果你想保留原Map中元素的插入顺序,可以把
HashMap换成LinkedHashMap,或者创建一个新的LinkedHashMap来存储去重结果,这样第一个出现的重复List对应的键值对会被保留。 - 自定义对象注意事项:如果List里存的是自定义对象,一定要确保这个对象正确实现了
equals()和hashCode()方法,否则Set无法识别内容相同的List。
另一种不修改原Map的方式
如果你不想改动原Map,可以创建一个新Map来存储去重后的结果,更安全:
Map<String, List<Integer>> uniqueMap = new LinkedHashMap<>(); Set<List<Integer>> seen = new HashSet<>(); for (Map.Entry<String, List<Integer>> entry : sample.entrySet()) { if (seen.add(entry.getValue())) { uniqueMap.put(entry.getKey(), entry.getValue()); } } // uniqueMap就是去重后的结果,原sample保持不变
内容的提问来源于stack exchange,提问作者tjkathiresan
相关产品推荐
相关产品推荐

