创建两个HashSet规则集,用户输入若干姓名作为元素,求它们的并、差和交 输入的用户名用逗号分隔 注意观察元素输出时的次序 并排序输出
时间: 2023-06-15 09:05:38 浏览: 91
以下是示例代码,创建了两个HashSet规则集,分别为set1和set2。用户输入的姓名列表用逗号分隔,通过split()方法将其转化为字符串数组,然后依次添加到set1中。对于set2的创建也是类似的。最后通过set1、set2的方法求得并集、差集和交集,并将结果排序输出。
```java
import java.util.*;
public class HashSetDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入第一个规则集的元素(姓名用逗号分隔):");
String names1 = scanner.nextLine();
System.out.print("请输入第二个规则集的元素(姓名用逗号分隔):");
String names2 = scanner.nextLine();
// 创建set1
Set<String> set1 = new HashSet<>();
String[] nameArr1 = names1.split(",");
for (String name : nameArr1) {
set1.add(name.trim()); // 去除空格并添加到set1中
}
// 创建set2
Set<String> set2 = new HashSet<>();
String[] nameArr2 = names2.split(",");
for (String name : nameArr2) {
set2.add(name.trim()); // 去除空格并添加到set2中
}
// 求并集
Set<String> union = new HashSet<>(set1);
union.addAll(set2);
System.out.print("并集为:");
printSortedSet(union);
// 求差集
Set<String> difference = new HashSet<>(set1);
difference.removeAll(set2);
System.out.print("差集为:");
printSortedSet(difference);
// 求交集
Set<String> intersection = new HashSet<>(set1);
intersection.retainAll(set2);
System.out.print("交集为:");
printSortedSet(intersection);
}
// 输出set中的元素,按字典序排序
public static void printSortedSet(Set<String> set) {
List<String> list = new ArrayList<>(set);
Collections.sort(list);
System.out.print("[ ");
for (String s : list) {
System.out.print(s + " ");
}
System.out.print("]\n");
}
}
```
示例输出:
```
请输入第一个规则集的元素(姓名用逗号分隔):张三, 李四, 王五, 赵六
请输入第二个规则集的元素(姓名用逗号分隔):李四, 王五, 钱七
并集为:[ 张三 李四 王五 赵六 钱七 ]
差集为:[ 张三 赵六 ]
交集为:[ 李四 王五 ]
```
阅读全文
相关推荐















