在 Java 8 中对两个Set集合取交集有几种常用写法我把性能和用法都列出来供你参考一、常用写法方法一retainAll()原地修改javaSetLong set1 new HashSet(Arrays.asList(1L, 2L, 3L, 4L)); SetLong set2 new HashSet(Arrays.asList(3L, 4L, 5L, 6L)); set1.retainAll(set2); // set1 被修改变成 {3, 4} System.out.println(set1); // [3, 4]特点✅ 效率高内部优化⚠️ 会修改原集合set1原数据丢失如果不想破坏原集合先复制一份再操作方法二Stream.filter()不修改原集合javaSetLong set1 new HashSet(Arrays.asList(1L, 2L, 3L, 4L)); SetLong set2 new HashSet(Arrays.asList(3L, 4L, 5L, 6L)); SetLong intersection set1.stream() .filter(set2::contains) .collect(Collectors.toSet()); System.out.println(intersection); // [3, 4]特点✅ 不修改原集合⚠️ 在大数据量下性能稍低于retainAll方法三new HashSet(set1)retainAll()不破坏原集合javaSetLong intersection new HashSet(set1); // 复制 intersection.retainAll(set2); // 取交集 System.out.println(intersection); // [3, 4]特点✅ 不修改原集合✅ 性能优秀接近retainAll推荐用于需要保留原集合的场景方法四SetUtils.intersection()Apache Commons / Hutooljava// Hutool SetLong intersection CollUtil.intersection(set1, set2); // 或者 Apache Commons SetLong intersection SetUtils.intersection(set1, set2);二、三种方式对比方式修改原集合性能推荐度set1.retainAll(set2)✅ 修改 set1最高⭐⭐⭐不介意修改原集合时new HashSet(set1).retainAll(set2)❌ 不修改高⭐⭐⭐⭐⭐推荐stream().filter().collect()❌ 不修改较高⭐⭐⭐⭐需要流式处理时HutoolCollUtil.intersection()❌ 不修改高⭐⭐⭐⭐⭐已引入 Hutool三、空集合的处理javaSetLong set1 Collections.emptySet(); SetLong set2 new HashSet(Arrays.asList(1L, 2L, 3L)); // 使用 Stream 方式空集合安全 SetLong intersection set1.stream() .filter(set2::contains) .collect(Collectors.toSet()); // 返回空集合 // 使用 retainAll 方式 SetLong intersection new HashSet(set1); // 空集合 intersection.retainAll(set2); // 仍然是空集合安全四、完整示例javaimport java.util.*; public class SetIntersectionDemo { public static void main(String[] args) { SetLong set1 new HashSet(Arrays.asList(1L, 2L, 3L, 4L, 5L)); SetLong set2 new HashSet(Arrays.asList(4L, 5L, 6L, 7L, 8L)); // 方式一不修改原集合推荐 SetLong result1 new HashSet(set1); result1.retainAll(set2); System.out.println(交集: result1); // [4, 5] // 方式二使用 Stream SetLong result2 set1.stream() .filter(set2::contains) .collect(Collectors.toSet()); System.out.println(交集: result2); // [4, 5] // 方式三使用 Hutool SetLong result3 CollUtil.intersection(set1, set2); System.out.println(交集: result3); // [4, 5] // 原始集合未被修改 System.out.println(set1: set1); // [1, 2, 3, 4, 5] System.out.println(set2: set2); // [4, 5, 6, 7, 8] } }五、推荐写法场景推荐不关心原集合追求性能set1.retainAll(set2)需要保留原集合new HashSet(set1).retainAll(set2)项目已引入 HutoolCollUtil.intersection(set1, set2)需要流式处理过滤/映射stream().filter().collect()