package com.itheima.test;
import java.util.HashSet;
public class Union {
public static void main(String[] args) {
HashSet<String> set1 = new HashSet<>();
HashSet<String> set2 = new HashSet<>();
set1.add("a");
set1.add("b");
set1.add("c");
set1.add("d");
System.out.println(set1);
set2.add("a");
set2.add("b");
set2.add("e");
System.out.println(set2);
HashSet<String> hashSetUnion = new HashSet<>();
hashSetUnion.addAll(set1);
hashSetUnion.addAll(set2);
System.out.println("并集是:");
System.out.println(hashSetUnion.toString());//并集
HashSet<String> sameSet = new HashSet<>();
for (String string : set1) {
if(set2.contains(string)){
sameSet.add(string);
}
}
System.out.println("交集是:");
System.out.println(sameSet.toString());//交集
}
}
Java-集合的交集和并集
最新推荐文章于 2024-10-03 10:58:56 发布