用java写给出两个整数集合A、B,求出他们的交集、并集以及B在A中的余集的程序
时间: 2023-11-28 15:48:22 浏览: 77
用于处理数据,求两个集合的交集、并集、补集。附源码。
```java
import java.util.HashSet;
import java.util.Set;
public class SetOperations {
public static Set<Integer> intersection(Set<Integer> setA, Set<Integer> setB) {
Set<Integer> intersectionSet = new HashSet<>(setA);
intersectionSet.retainAll(setB);
return intersectionSet;
}
public static Set<Integer> union(Set<Integer> setA, Set<Integer> setB) {
Set<Integer> unionSet = new HashSet<>(setA);
unionSet.addAll(setB);
return unionSet;
}
public static Set<Integer> complement(Set<Integer> setA, Set<Integer> setB) {
Set<Integer> complementSet = new HashSet<>(setA);
complementSet.removeAll(setB);
return complementSet;
}
public static void main(String[] args) {
Set<Integer> setA = new HashSet<>();
setA.add(1);
setA.add(2);
setA.add(3);
Set<Integer> setB = new HashSet<>();
setB.add(2);
setB.add(3);
setB.add(4);
// intersection
Set<Integer> intersection = intersection(setA, setB);
System.out.println("Intersection: " + intersection);
// union
Set<Integer> union = union(setA, setB);
System.out.println("Union: " + union);
// complement
Set<Integer> complement = complement(setA, setB);
System.out.println("Complement of B in A: " + complement);
}
}
```
输出结果为:
```
Intersection: [2, 3]
Union: [1, 2, 3, 4]
Complement of B in A: [1]
```
阅读全文