retainAll方法用于计算集合交集并保留共有的元素,调用后原集合被修改;Set去重适合求交集,List保留重复元素且顺序不变;若需保持原集合不变,应先复制再操作。

在Java中,retainAll 方法用于保留当前集合中也存在于指定集合中的元素,换句话说,它会计算两个集合的交集,并将结果保留在调用该方法的集合中。
retainAll方法的基本用法
retainAll 是 Collection 接口定义的方法,常见于 List、Set 等实现类。调用后,原集合会被修改,只保留与目标集合共有的元素。
语法:
boolean retainAll(Collection> c)返回 true 表示集合内容发生了变化(有元素被移除或保留),否则返回 false。
立即学习“Java免费学习笔记(深入)”;
使用Set获取交集(推荐方式)
Set 集合天然去重,适合做交集操作。以下是一个使用 HashSet 的例子:
Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3, 4));Set<Integer> set2 = new HashSet<>(Arrays.asList(3, 4, 5, 6));
set1.retainAll(set2);
System.out.println(set1); // 输出 [3, 4]
执行后,set1 中只剩下 3 和 4,即两个集合的交集。
使用List时的注意事项
List 也可以调用 retainAll,但行为略有不同:会保留所有匹配的元素,包括重复项,且顺序不变。
List<String> list1 = new ArrayList<>(Arrays.asList("a", "b", "c", "b"));List<String> list2 = new ArrayList<>(Arrays.asList("b", "c", "d"));
list1.retainAll(list2);
System.out.println(list1); // 输出 [b, c, b]
注意:虽然 "b" 在 list2 中只出现一次,但 list1 中保留了两次,因为 list 不去重。
保持原集合不变的操作方式
如果不想修改原始集合,可以先复制一份再操作:
Set<Integer> originalSet = new HashSet<>(Arrays.asList(1, 2, 3));Set<Integer> otherSet = new HashSet<>(Arrays.asList(2, 3, 4));
Set<Integer> intersection = new HashSet<>(originalSet);
intersection.retainAll(otherSet);
System.out.println(intersection); // [2, 3]
System.out.println(originalSet); // [1, 2, 3](未改变)
基本上就这些。retainAll 是获取交集的便捷方法,使用时注意集合类型和是否需要保留原数据。对于数学意义上的交集,优先使用 Set。操作完成后,原集合会被修改,如需保留原始数据,记得先复制。不复杂但容易忽略这一点。










