集合1 2 3 4 和集合3 4 5 6求两集合的并集,交集和差集,用java语音
时间: 2023-06-24 10:07:41 浏览: 195
下面是用 Java 语言实现求两个集合的并集、交集和差集的代码:
```java
import java.util.*;
public class SetOperations {
public static void main(String[] args) {
Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3, 4));
Set<Integer> set2 = new HashSet<>(Arrays.asList(3, 4, 5, 6));
// 求并集
Set<Integer> union = new HashSet<>(set1);
union.addAll(set2);
System.out.println("Set union: " + union);
// 求交集
Set<Integer> intersection = new HashSet<>(set1);
intersection.retainAll(set2);
System.out.println("Set intersection: " + intersection);
// 求差集
Set<Integer> difference1 = new HashSet<>(set1);
difference1.removeAll(set2);
System.out.println("Set difference (set1 - set2): " + difference1);
Set<Integer> difference2 = new HashSet<>(set2);
difference2.removeAll(set1);
System.out.println("Set difference (set2 - set1): " + difference2);
}
}
```
输出结果为:
```
Set union: [1, 2, 3, 4, 5, 6]
Set intersection: [3, 4]
Set difference (set1 - set2): [1, 2]
Set difference (set2 - set1): [5, 6]
```
阅读全文
相关推荐
![](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)