Java8 steam list object 取差值、交集

package com.atguigu.mybatisx.test;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class ListObjTest {
    public static void main(String[] args) {

        List<User> oldList = new ArrayList<>();
        List<User> newList = new ArrayList<>();

        User old1 = new User(1,1);
        User old2 = new User(2,3);
        oldList.add(old1);
        oldList.add(old2);

        User new1 = new User(1,1);
        User new2 = new User(2,3);
        User new3 = new User(3,2);
        User new4 = new User(4,8);
        newList.add(new1);
        newList.add(new2);
        newList.add(new3);
        newList.add(new4);

        // newList 取差值
        List<User> collect = newList.stream().filter(item -> !oldList.stream().map(m -> m.getUserId()+"|"+m.getCourseId()).collect(Collectors.toList()).contains(item.getUserId()+"|"+item.getCourseId())).collect(Collectors.toList());
        System.out.println("取差值");
        collect.stream().forEach(item -> {
            System.out.println(item.getUserId()+","+item.getCourseId());
        });

        // newList 取交集
        System.out.println("取交集");
        List<User> collect2 = newList.stream().filter(item -> oldList.stream().map(m -> m.getUserId()+"|"+m.getCourseId()).collect(Collectors.toList()).contains(item.getUserId()+"|"+item.getCourseId())).collect(Collectors.toList());
        collect2.stream().forEach(item -> {
            System.out.println(item.getUserId()+","+item.getCourseId());
        });


    }

    static class User{
        private int userId;
        private int courseId;

        public User(int userId, int courseId) {
            this.userId = userId;
            this.courseId = courseId;
        }

        public int getUserId() {
            return userId;
        }

        public void setUserId(int userId) {
            this.userId = userId;
        }

        public int getCourseId() {
            return courseId;
        }

        public void setCourseId(int courseId) {
            this.courseId = courseId;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值