java求两集合不同元素的集合
时间: 2023-06-24 15:03:10 浏览: 53
可以使用Java中的Set集合来求解两个集合的不同元素的集合。具体步骤如下:
1. 定义两个Set集合分别存放两个集合的元素。
```java
Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
Set<Integer> set2 = new HashSet<>(Arrays.asList(3, 4, 5, 6, 7));
```
2. 复制两个Set集合,然后从复制的集合中移除两个集合的交集。
```java
Set<Integer> copySet1 = new HashSet<>(set1);
copySet1.removeAll(set2); // 移除set1和set2的交集
Set<Integer> copySet2 = new HashSet<>(set2);
copySet2.removeAll(set1); // 移除set1和set2的交集
```
3. 将两个复制后的集合合并成一个集合作为结果。
```java
Set<Integer> result = new HashSet<>(copySet1);
result.addAll(copySet2); // 合并两个不同元素的集合
```
完整代码如下:
```java
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class DifferentElements {
public static void main(String[] args) {
Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
Set<Integer> set2 = new HashSet<>(Arrays.asList(3, 4, 5, 6, 7));
Set<Integer> copySet1 = new HashSet<>(set1);
copySet1.removeAll(set2);
Set<Integer> copySet2 = new HashSet<>(set2);
copySet2.removeAll(set1);
Set<Integer> result = new HashSet<>(copySet1);
result.addAll(copySet2);
System.out.println("集合1:" + set1);
System.out.println("集合2:" + set2);
System.out.println("不同元素的集合:" + result);
}
}
```
输出结果为:
```
集合1:[1, 2, 3, 4, 5]
集合2:[3, 4, 5, 6, 7]
不同元素的集合:[1, 2, 6, 7]
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)