最直接的方式是用addall()方法逐个添加,hashset自动去重;也可用stream api的flatmap+collect合并,需显式指定hashset::new确保类型;两者均不修改原集合,但要求自定义类正确实现equals和hashcode。

Java 中 HashSet 合并多个集合并去重,最直接的方式是用 addAll() 方法逐个添加,HashSet 本身会自动保证元素唯一性。
用 addAll() 合并多个 HashSet
这是最常用、最简洁的做法。创建一个空的 HashSet,然后对每个待合并的集合调用 addAll():
- 所有重复元素会被自动忽略,无需额外去重逻辑
- 时间复杂度接近 O(n),效率高
- 注意:被添加的集合不能为
null,否则抛NullPointerException
HashSet<string> set1 = new HashSet(Arrays.asList("a", "b", "c"));
HashSet<string> set2 = new HashSet(Arrays.asList("b", "c", "d"));
HashSet<string> set3 = new HashSet(Arrays.asList("c", "d", "e"));
HashSet<string> merged = new HashSet();
merged.addAll(set1);
merged.addAll(set2);
merged.addAll(set3);
// 结果:[a, b, c, d, e](顺序不保证)
</string></string></string></string>
用 Stream API 合并(Java 8+)
适合链式操作或需要中间处理的场景,可一次性合并任意数量集合:
- 用
Stream.of()把多个集合转为流,再用flatMap(Collection::stream)扁平化 - 最后用
collect(Collectors.toSet())收集为 HashSet(也可用toCollection(HashSet::new)明确指定) - 注意:
Collectors.toSet()不保证返回 HashSet,若需确保类型,建议显式构造
Set<string> merged = Stream.of(set1, set2, set3)
.flatMap(Collection::stream)
.collect(Collectors.toCollection(HashSet::new));
</string>
合并时保留原始集合不变
上述方法都不会修改原集合(addAll() 修改的是目标集合,源集合只读),但要注意:
- 如果某个源集合本身是其他集合的引用或视图(如
Collections.unmodifiableSet()),addAll()仍能正常读取,不会报错 - 若需深拷贝对象(比如集合里是可变对象),HashSet 只复制引用,不复制对象内容;去重仍基于
equals()和hashCode(),请确保自定义类正确定义这两个方法
处理 null 元素和自定义类型
HashSet 允许存一个 null,但多个集合中若有多个 null,最终也只保留一个:
- 如果集合含
null,addAll()和 Stream 方式都兼容 - 对于自定义类,必须重写
equals()和hashCode(),否则即使字段相同也会被视为不同元素 - 例如:两个
User对象 id 相同但未重写hashCode(),HashSet 会当作两个不同元素
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











