2用Java.创建两个集合{"lily", "tom", "John", "Kevin"}和{"George", "Rose", "tom", "Helena"},求它们的并、交和差。
时间: 2023-12-11 13:33:19 浏览: 19
以下是Java中求两个集合的并、交和差的例子:
```java
import java.util.*;
public class SetOperations {
public static void main(String[] args) {
Set<String> set1 = new HashSet<>(Arrays.asList("lily", "tom", "John", "Kevin"));
Set<String> set2 = new HashSet<>(Arrays.asList("George", "Rose", "tom", "Helena"));
// 求并集
Set<String> union = new HashSet<>(set1);
union.addAll(set2);
System.out.println("Union: " + union);
// 求交集
Set<String> intersection = new HashSet<>(set1);
intersection.retainAll(set2);
System.out.println("Intersection: " + intersection);
// 求差集
Set<String> difference = new HashSet<>(set1);
difference.removeAll(set2);
System.out.println("Difference: " + difference);
}
}
```
输出结果为:
```
Union: [John, Kevin, George, Rose, tom, lily, Helena]
Intersection: [tom]
Difference: [John, Kevin, lily]
```