Java 中 List 集合取补集

交集 Intersection 英 [ˌɪntəˈsekʃn]
并集 Union 英 [ˈjuːniən]
差集 difference of set
补集 complement set 英 [ˈkɒmplɪment]
Java 中 List 集合取交集
Java 中 List 集合取并集
Java 中 List 集合取差集
Java 中 List 集合取补集


# 求两个集合交集的补集
List<Integer> list1 = new ArrayList(Arrays.asList(1, 2, 3));
List<Integer> list2 = new ArrayList(Arrays.asList(3, 6, 7, 8, 9));

List<Integer> list3 = new ArrayList(list1);
list3.removeAll(list2);
List<Integer> list4 = new ArrayList(list2);
list4.removeAll(list1);
list3.addAll(list4);

list1 :[1, 2, 3]
list2 :[3, 6, 7, 8, 9]
求两个集合交集的补集:[1, 2, 6, 7, 8, 9]
# 求两个集合交集的补集
List<Integer> list1 = new ArrayList(Arrays.asList(1, 2, 3));
List<Integer> list2 = new ArrayList(Arrays.asList(3, 6, 7, 8, 9));

Collection s1 = CollectionUtils.subtract(list1, list2);
Collection s2 = CollectionUtils.subtract(list2, list1);
Collection union = CollectionUtils.union(s1, s2);

list1 :[1, 2, 3]
list2 :[3, 6, 7, 8, 9]
求两个集合交集的补集:[1, 2, 6, 7, 8, 9]
# 求集合list1相对于List1和list2全集的补集
List<Integer> list1 = new ArrayList(Arrays.asList(1, 2, 3));
List<Integer> list2 = new ArrayList(Arrays.asList(3, 6, 7, 8, 9));

List<Integer> union = new ArrayList(list1);
union.addAll(list2);
union.removeAll(list1);

list1 :[1, 2, 3]
list2 :[3, 6, 7, 8, 9]
list1 的补集:[6, 7, 8, 9]

猜你喜欢

转载自blog.csdn.net/weixin_37646636/article/details/132713502