Java 集合List取补集

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

求两个集合交集的补集

方法1:removeAll

# 求两个集合交集的补集
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]
交集:     [3]
交集的补集:[1, 2, 6, 7, 8, 9]

方法2:subtract

# 求两个集合交集的补集
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]

方法3:disjunction

List<Integer> list1 = new ArrayList(Arrays.asList(1, 2, 3));
List<Integer> list2 = new ArrayList(Arrays.asList(3, 6, 7, 8, 9));
Collection disjunction = CollectionUtils.disjunction(list1, list2);

求两个集合交集的补集:[1, 2, 6, 7, 8, 9]

求集合list1相对于List1和list2全集的补集

# 求集合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]

参考:
java 集合交集、并集、差集、补集1
java 集合交集、并集、差集、补集2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值