一、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());