Stream对两个List求取并集、交集、补集

public static void main(String[] args) {
        TestVo testVo0 = new TestVo("0", "A", "~", "@");
        TestVo testVo1 = new TestVo("1", "B", "~", "@");
        TestVo testVo2 = new TestVo("2", "C", "~", "@");
        TestVo testVo3 = new TestVo("3", "D", "~", "@");

        List<TestVo> list1 = new ArrayList<>();
        list1.add(testVo0);
        list1.add(testVo1);
        list1.add(testVo2);
        list1.add(testVo3);

        TestVo testVo4 = new TestVo("0", "V", "~", "@");
        TestVo testVo5 = new TestVo("1", "F", "~", "@");
        TestVo testVo6 = new TestVo("4", "C", "~", "@");
        TestVo testVo7 = new TestVo("5", "D", "~", "@");

        List<TestVo> list2 = new ArrayList<>();
        list2.add(testVo4);
        list2.add(testVo5);
        list2.add(testVo6);
        list2.add(testVo7);

        //并集(不去重)
        List<TestVo> allList1 = list1.parallelStream().collect(Collectors.toList());
        List<TestVo> allList2 = list2.parallelStream().collect(Collectors.toList());
        List< TestVo> allList = new ArrayList<> ();
        allList.addAll(allList1);
        allList.addAll(allList2);
        System.out.println(allList);

        //交集1
        List<TestVo> collectVo = list1.stream().filter(item ->
                list2.stream().map(TestVo::getId).collect(Collectors.toList()).contains(item.getId())
        ).collect(Collectors.toList());
        collectVo.forEach(System.out::println);
        
		//交集2
        List<TestVo> collect = list1.stream().filter(item ->{
            for (TestVo tvo1 : list2) {
                if (item.getId().equals(tvo1.getId())) {
                    return true;
                }
            }
            return false;
        }).collect(Collectors.toList());
        collect.forEach(System.out::println);

        //补集
        List<TestVo> collectVo2 = list1.stream().filter(testVo -> {
            for (TestVo tvo : list2) {
                if (testVo.getId().equals(tvo.getId())) {
                    return false;
                }
            }
            return true;
        }).collect(Collectors.toList());

        collectVo2.forEach(System.out::println);
    }
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值