CollectionUtils工具类之并集union(arr1,arr2)和差集subtract(arr1,arr2)

一、CollectionUtils工具类之并集union(arr1,arr2)和差集subtract(arr1,arr2)

采用的类:

import org.apache.commons.collections4.CollectionUtils;

①并集union(arr1,arr2)

这是将两个集合加在一起,然后去重

List<Integer> orderList1 = Arrays.asList(1, 2, 3);

List<Integer> orderList2 = Arrays.asList(3, 4, 5);

List<Integer> union = new ArrayList<>(CollectionUtils.union(orderList1, orderList2)); 

// 1,2,3,4,5
System.out.println("union = " + union);

 

②差集subtract(arr1,arr2)

这是将两个集合的差,如1,2,3 差集3,4,5就会得到1,2,将3这个重复的去掉

List<Integer> orderList1 = Arrays.asList(1, 2, 3);

List<Integer> orderList2 = Arrays.asList(3, 4, 5);

List<Integer> subtract = new ArrayList<>(CollectionUtils.subtract (orderList1, orderList2));

// 1,2
System.out.println("subtract = " + subtract );

③遇到的问题

返回值是父级的Collection<O>,这样的话如果只想做合并去重的话就会导致类型不一致,而照成麻烦

List<Integer> orderList1 = Arrays.asList(1, 2, 3);

List<Integer> orderList2 = Arrays.asList(3, 4, 5);
Collection
<Integer> union = CollectionUtils.union(orderList1, orderList2);
// 1,2,3,4,5 System.out.println("union = " + union);

如需要转换为对应的类型,如上转回List<Integer>可以有几种方案

方案1

List<Integer> union = new ArrayList<>(CollectionUtils.union(orderList1, orderList2));

方案2

// 这个会警告,我们这里是加了一个.distinct()做过度
List<Integer> union1 = CollectionUtils.union(orderList1, orderList2).stream().collect(Collectors.toList());

 

posted @ 2022-01-27 11:47  骚哥  阅读(1931)  评论(0编辑  收藏  举报