java获取两个list集合的并集、交集、交集的补集、差集
2022-09-08 本文已影响0人
King斌
1、maven
包依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.1</version>
</dependency>
2、具体代码
public class demo {
//两个集合也可以是对象集合
public static void main(String[] args) {
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
String String1 = new String("1");
String String2 = new String("2");
String String3 = new String("1");
String String4 = new String("4");
list1.add(String1);
list1.add(String2);
list2.add(String3);
list2.add(String4);
List<String> union = getUnion(list1,list2);
System.out.println("并集:"+union);
List<String> intersection = getIntersection(list1,list2);
System.out.println("交集:"+intersection);
List<String> disjunction = getDisjunction(list1,list2);
System.out.println("交集的补集:"+disjunction);
List<String> subtract = getSubtract(union,list1);
System.out.println("差集:"+subtract);
}
//获取两个集合并集(自动去重)
public static List<String> getUnion(List<String> list1, List<String> list2){
List<String> union = (List<String>) CollectionUtils.union(list1, list2);
return union;
}
//获取两个集合交集
public static List<String> getIntersection(List<String> list1,List<String> list2){
List<String> intersection = (List<String>)CollectionUtils.intersection(list1, list2);
return intersection;
}
//获取两个集合交集的补集 即 list1 + list2 - 交集
public static List<String> getDisjunction(List<String> list1,List<String> list2){
List<String> disjunction = (List<String>)CollectionUtils.disjunction(list1, list2);
return disjunction;
}
//获取两个集合的差集 list1 - 交集
public static List<String> getSubtract(List<String> list1,List<String> list2){
List<String> subtract = (List<String>)CollectionUtils.subtract(list1, list2);
return subtract;
}
}
运行结果:
image.png