给出两个无序整数集合A、B,求出他们的交集、并集以及B在A中的余集,输出从小到大。用Java实现
时间: 2023-11-28 19:48:33 浏览: 90
用于处理数据,求两个集合的交集、并集、补集。附源码。
可以使用Java的集合类来实现交集、并集和差集的计算。以下是示例代码:
```java
import java.util.*;
public class SetOperations {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Set<Integer> setA = new HashSet<>();
Set<Integer> setB = new HashSet<>();
System.out.print("Enter elements of set A separated by space: ");
String[] inputA = sc.nextLine().split(" ");
for (String s : inputA) {
setA.add(Integer.parseInt(s));
}
System.out.print("Enter elements of set B separated by space: ");
String[] inputB = sc.nextLine().split(" ");
for (String s : inputB) {
setB.add(Integer.parseInt(s));
}
// Intersection
Set<Integer> intersection = new HashSet<>(setA);
intersection.retainAll(setB);
System.out.println("Intersection: " + intersection);
// Union
Set<Integer> union = new HashSet<>(setA);
union.addAll(setB);
System.out.println("Union: " + union);
// Difference
Set<Integer> difference = new HashSet<>(setB);
difference.removeAll(setA);
System.out.println("B complement A: " + difference);
}
}
```
示例输入输出:
```
Enter elements of set A separated by space: 1 2 3 4
Enter elements of set B separated by space: 3 4 5 6
Intersection: [3, 4]
Union: [1, 2, 3, 4, 5, 6]
B complement A: [5, 6]
```
阅读全文