在 Java 中,Set 求交集(intersection)常见有 多种方式,下面按“是否修改原集合”和“Java 版本”给你总结。
retainAll(最常用 ⭐)Set<String> set1 = new HashSet<>(Arrays.asList("A", "B", "C"));
Set<String> set2 = new HashSet<>(Arrays.asList("B", "C", "D"));
set1.retainAll(set2);
System.out.println(set1); // [B, C]
✅ set1 变成了交集
❌ set2 不变,set1 被修改
Set<String> set1 = new HashSet<>(Arrays.asList("A", "B", "C"));
Set<String> set2 = new HashSet<>(Arrays.asList("B", "C", "D"));
Set<String> intersection = new HashSet<>(set1);
intersection.retainAll(set2);
System.out.println(intersection); // [B, C]
Set<String> intersection = set1.stream()
.filter(set2::contains)
.collect(Collectors.toSet());
✅ 不修改原集合
⚠️ set2 最好是 HashSet,否则性能差
Set<String> intersection = set1.parallelStream()
.filter(set2::contains)
.collect(Collectors.toSet());
Set<String> intersection = Sets.intersection(set1, set2);
✅ 不修改原集合
✅ 语义清晰
| 方式 | 时间复杂度 |
|---|---|
| retainAll | O(n) |
| stream filter | O(n) |
| Guava intersection | O(n) |
| 场景 | 推荐方式 |
|---|---|
| 不在乎修改原集合 | retainAll |
| 想保留原集合 | copy + retainAll |
| 函数式风格 | Stream |
| 项目用 Guava | Sets.intersection |
如果你用的是 特定 Set 类型(TreeSet / EnumSet) 或 超大集合,我也可以给你更优方案。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。