java 两个列表的求交集、差集和并集

import java.util.HashSet;  
import java.util.List;  
import java.util.Set;  
  
public class SetOperations {  
    public static void main(String[] args) {  
        // 创建两个列表  
        List<String> list1 = Arrays.asList("a", "b", "c", "d");  
        List<String> list2 = Arrays.asList("b", "c", "e", "f");  
  
        // 求交集  
        Set<String> intersection = new HashSet<>(list1);  
        intersection.retainAll(list2);  
        System.out.println("交集: " + intersection);  
  
        // 求并集  
        Set<String> union = new HashSet<>(list1);  
        union.addAll(list2);  
        System.out.println("并集: " + union);  
  
        // 求差集 (list1 - list2)  
        Set<String> difference = new HashSet<>(list1);  
        difference.removeAll(list2);  
        System.out.println("差集 (list1 - list2): " + difference);  
  
        // 求差集 (list2 - list1)  
        Set<String> difference2 = new HashSet<>(list2);  
        difference2.removeAll(list1);  
        System.out.println("差集 (list2 - list1): " + difference2);  
    }  
}