java 两个列表的求交集、差集和并集
原创
©著作权归作者所有:来自51CTO博客作者潇凝子潇的原创作品,请联系作者获取转载授权,否则将追究法律责任
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);
}
}