问题:在多个集合中找出都存在的元素
方法:1 利用contains进行元素判断是否存在
2 利用 retainAll方法获取两个集合的交集
代码如下
public static void main(String[] args) {
HashSet<String> meterRace1 = new HashSet<String>(Arrays.asList("赵子龙", "凯", "鲁班", "孙膑", "王昭君", "马超"));
HashSet<String> meterRace2 = new HashSet<String>(Arrays.asList("孙尚香", "李白", "盘古", "雷迅", "小米", "马超"));
HashSet<String> meterRace3 = new HashSet<String>(Arrays.asList("雷军", "马化腾", "盘古", "孙膑", "张飞", "马超"));
// 方法一 :使用1中集合中的每个集合 去和2,3中的集合进行对比查找
// 遍历1中的元素
for (String name : meterRace1) {
对比方式1 : name在2,3中的集合中是否存在
if (meterRace2.contains(name) && meterRace3.contains(name)) {
System.out.println(name);
}
// 对比方式1 : 利用add方法检查添加结果 如果存在则返回false 不存在返回 true
if (!meterRace2.add(name) && !meterRace3.add(name)) {
System.out.println(name);
}
}
//方法二 :利用 retainAll方法获取两个集合的交集
meterRace1.retainAll(meterRace2);
meterRace1.retainAll(meterRace3);
System.out.println(meterRace1);
}
运行结果如下
[马超]
这篇博客探讨了如何在Java中处理多个集合,找出它们之间的共同元素。通过使用contains方法进行元素判断以及retainAll方法获取交集,实现集合元素的筛选。文章提供了具体的代码示例并展示了运行结果。
1484

被折叠的 条评论
为什么被折叠?



