代码:
public class Test {
public static void main(String[] args) {
Set<String> a = new HashSet<>();
a.add("1");
a.add("2");
Set<String> b = new HashSet<>();
b.add("2");
b.add("3");
// 输出原始数据
System.out.println("原始数据1:" + a);
System.out.println("原始数据2:" + b);
// 并集
Set<String> bingJi = new HashSet<>(a);
bingJi.addAll(b);
System.out.println("并集:" + bingJi);
// 差集
Set<String> chaJi = new HashSet<>(a);
chaJi.removeAll(b);
System.out.println("差集:" + chaJi);
// 交集
Set<String> jiaoJi = new HashSet<>(a);
jiaoJi.retainAll(b);
System.out.println("交集:" + jiaoJi);
// 补集
Set<String> buJi = new HashSet<>(bingJi);
buJi.removeAll(a);
System.out.println("补集:" + buJi);
// 对称差集
Set<String> duiChenChaJi = new HashSet<>(bingJi);
duiChenChaJi.removeAll(jiaoJi);
System.out.println("对称差集:" + duiChenChaJi);
}
}
结果:
原始数据1:[1, 2]
原始数据2:[2, 3]
并集:[1, 2, 3]
差集:[1]
交集:[2]
补集:[3]
对称差集:[1, 3]