?一、依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
二、工具类
import org.apache.commons.collections4.CollectionUtils;
import java.util.List;
public class ListUtils {
//获取两个集合并集(自动去重)
public static <T> List<T> getUnion(List<T> list1, List<T> list2){
List<T> union = (List<T>) CollectionUtils.union(list1, list2);
return union;
}
//获取两个集合交集
public static <T> List<T> getIntersection(List<T> list1,List<T> list2){
List<T> intersection = (List<T>) CollectionUtils.intersection(list1, list2);
return intersection;
}
//获取两个集合交集的补集 即 list1 + list2 - 交集
public static <T> List<T> getDisjunction(List<T> list1,List<T> list2){
List<T> disjunction = (List<T>)CollectionUtils.disjunction(list1, list2);
return disjunction;
}
//获取两个集合的差集 list1 - 交集
public static <T> List<T> getSubtract(List<T> list1,List<T> list2){
List<T> subtract = (List<T>)CollectionUtils.subtract(list1, list2);
return subtract;
}
}
三、测试
public static void main(String[] args) {
List<Integer> list1 = Stream.of(1, 2, 3).collect(Collectors.toList());
List<Integer> list2 = Stream.of(2, 3, 4).collect(Collectors.toList());
System.out.println("list1:" + list1);
System.out.println("list2:" + list2);
List<Integer> union = getUnion(list1, list2);
System.out.println("list1-list2并集union:" + union);
List<Integer> intersection = getIntersection(list1, list2);
System.out.println("list1,-list2交集:" + intersection);
List<Integer> disjunction = getDisjunction(list1, list2);
System.out.println("list1-list2交集的补集:" + disjunction);
List<Integer> subtract = getSubtract( union,list1);
System.out.println("union-list1差集:" + subtract);
}
list1:[1, 2, 3]
list2:[2, 3, 4]
list1-list2并集union:[1, 2, 3, 4]
list1,-list2交集:[2, 3]
list1-list2交集的补集:[1, 4]
union-list1差集:[4]
|