两个List对象多属性去重、交集、差集

两个List对象多属性去重、交集、差集

public class Test {



    public static void main(String[] args) {
        People people1 = new People("admin","1","14");
        People people2 = new People("admin","2","11");
        People people5 = new People("zhangsan","1","11");

        People people3 = new People("admin2","3","12");
        People people4 = new People("admin","1","2");
        People people6 = new People("zhangsan","2","2");

        ArrayList<People> list = new ArrayList<>();
        list.add(people1);
        list.add(people2);
        list.add(people5);
        ArrayList<People> list2 = new ArrayList<>();
        list2.add(people3);
        list2.add(people4);
        list2.add(people6);

        // 交集
        List<People> updList = list.stream()
                .filter(item -> list2.stream().map(e -> e.getCode() + "&" + e.getName())
                        .collect(Collectors.toList()).contains(item.getCode()+ "&" + item.getName()))
//                .filter(item -> list2.stream().map(People::getName)
//                        .collect(Collectors.toList()).contains(item.getName()))
                .collect(Collectors.toList());

        // 差集
        List<People> updList2 = list.stream()
                .filter(item -> !list2.stream().map(e -> e.getCode() + e.getName())
                        .collect(Collectors.toList()).contains(item.getCode() + item.getName()))
//                .filter(item -> !list2.stream().map(People::getName)
//                        .collect(Collectors.toList()).contains(item.getName()))
                .collect(Collectors.toList());

        System.out.println(JSON.toJSONString(updList2));


        list.addAll(list2);
        //多属性去重
        List lst = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(

                () -> new TreeSet<>(Comparator.comparing(o -> o.getName() + "#" + o.getAge() ))),

                ArrayList::new));

        System.out.println(JSON.toJSONString(lst));

    }


    static class People{
        //姓名
        private String name;
        //身份证
        private String code;
        private String age;

        public People(String name, String code, String age) {
            this.name = name;
            this.code = code;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getAge() {
            return age;
        }

        public void setAge(String age) {
            this.age = age;
        }
    }



}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值