java 从两个集合中找出非交集
时间: 2024-05-09 16:19:15 浏览: 11
可以使用Java中的Set集合来实现找出两个集合的非交集。
示例代码如下:
```java
import java.util.HashSet;
import java.util.Set;
public class NonIntersection {
public static void main(String[] args) {
Set<Integer> set1 = new HashSet<>();
set1.add(1);
set1.add(2);
set1.add(3);
set1.add(4);
Set<Integer> set2 = new HashSet<>();
set2.add(3);
set2.add(4);
set2.add(5);
set2.add(6);
Set<Integer> nonIntersection = new HashSet<>(set1); // 先将set1添加到nonIntersection中
nonIntersection.removeAll(set2); // 再从nonIntersection中移除set2中包含的元素
System.out.println("set1:" + set1);
System.out.println("set2:" + set2);
System.out.println("非交集:" + nonIntersection);
}
}
```
输出结果为:
```
set1:[1, 2, 3, 4]
set2:[3, 4, 5, 6]
非交集:[1, 2]
```
在上面的示例代码中,首先将set1中的所有元素添加到nonIntersection中,然后使用removeAll()方法从nonIntersection中移除set2中包含的元素,最终得到的nonIntersection就是两个集合的非交集。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)