java,集合的问题,关于求并交,差集

【问题描述】设A和B为两个集合,A={a,b,c,d},B={b,c,d,e},则A与B的并集为:{a,b,c,d,e,f};

A与B的差集为:{a,b};A与B的交集为:{c,d}。

请编程,创建两个HashSet对象,其中保存整数。然后求它们的并集、差集和交集。

提示:利用addAll()、removeAll()、retainAll()方法。

请查阅帮助文档,了解Collection接口中这几个方法的用法。
【输入形式】

第1行是第1个HashSet对象的元素,0 表示结束

第2行是第2个HashSet对象的元素,0 表示结束
【输出形式】

两个集合的并集中的元素,用空格分隔

两个集合的差集中的元素,用空格分隔

两个集合的交集中的元素,用空格分隔
【样例输入】

1 2 3 4 0

3 4 5 6 0
【样例输出】

1 2 3 4 5 6

1 2

3 4

package Work1;

import java.util.HashSet;
import java.util.Scanner;

public class Homework61 {

public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    
    
    HashSet<Integer> A=new HashSet<Integer>();
    while(sc.hasNext()) {
        int obj=sc.nextInt();
        if( obj==0) {
            break;
            
        }else {
            A.add(obj);
        }
    }
    HashSet<Integer> B=new HashSet<Integer>();
    while(sc.hasNext()) {
        int c=sc.nextInt();
        if( c==0) {
            break;
            
        }else {
            B.add(c);
        }
    }
    HashSet<Integer>D =new HashSet<Integer>(); 
        D.addAll(B);
        D.addAll(A);
        String D1 = D.toString().replace("[", "").replace("]", "").replace(",", "");
        System.out.println(D1);

       D.addAll(A);
      
        D.removeAll(B);
        String D2 = D.toString().replace("[", "").replace("]", "").replace(",", "");
        System.out.println(D2);           
      


       D.addAll(A);
       D.addAll(B);
       D.retainAll(B);
        D.retainAll(A);
        String D3 = D.toString().replace("[", "").replace("]", "").replace(",", "");
        System.out.println(D3);
    
}

}

用流来处理很方便


代码如下:

List<Integer> list = new ArrayList<>(Arrays.asList(7, 8, 9));
List<Integer> list2 = new ArrayList<>(Arrays.asList(3,4, 9));

//交集
 List<Integer> beMixed = list.stream().filter(list2::contains).collect(Collectors.toList());
 System.out.println(beMixed);//[9]

//并集
List<Integer> aggregate = Stream.of(list, list2).flatMap(Collection::stream).distinct().collect(Collectors.toList());
System.out.println(aggregate);//[7, 8, 9, 3, 4]

//差集
List<Integer> subtraction = list.stream().filter(v->!list2.contains(v)).collect(Collectors.toList());
System.out.println(subtraction);//[7, 8]