过滤两个list集合中间的重复元素

注:整理自如何使用Java List等集合类的removeAll方法Java中找到两个list中的不同元素

  1. 使用 boolean removeAll(Collection<?> c)方法,从列表中移除指定 collection 中包含的其所有元素(可选操作)。
  2. 执行removeAll方法时,会先对集合元素进行比较(equals),如果元素相等执行移除操作。
    @Test
    public void test5(){
        List<Student> oldList = new ArrayList<>();
        oldList.add(new Student(12,"小胡"));
        oldList.add(new Student(13,"小博"));
        oldList.add(new Student(14,"小芳"));
        oldList.add(new Student(15,"小时"));
        List<Student> newList = new ArrayList<>();
        newList.add(new Student(16,"小胡1"));
        newList.add(new Student(13,"小博1"));
        newList.add(new Student(14,"小芳1"));
        newList.add(new Student(18,"小时1"));
        newList.removeAll(oldList);
        System.out.println(newList);
    }

当然,对于筛选条件,可以重写对象的equals方法;规定相等的条件。
例如,规定只需要年龄相等,就算是重复元素

package com.synda.boot.basic;

import lombok.Data;

@Data
public class Student {
    private Integer age;
    private String name;

    public Student(Integer age) {
        this.age = age;
    }

    public Student(Integer age, String name) {
        this.age = age;
        this.name = name;
    }

    public Student() {
    }


    @Override
    public boolean equals(Object obj){
        if (obj==null) return false;
        if (! (obj instanceof Student)) return false;
        Student student = (Student) obj;
        return this.age == student.getAge();
    }

}

在贴两段源码

 public boolean removeAll(Collection<?> c) {
        boolean modified = false;
        Iterator<?> it = iterator();
        while (it.hasNext()) {
            if (c.contains(it.next())) {
                it.remove();
                modified = true;
            }
        }
        return modified;
    }
public boolean remove(Object o) {
        Iterator<E> it = iterator();
        if (o==null) {
            while (it.hasNext()) {
                if (it.next()==null) {
                    it.remove();
                    return true;
                }
            }
        } else {
            while (it.hasNext()) {
                if (o.equals(it.next())) {
                    it.remove();
                    return true;
                }
            }
        }
        return false;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

synda@hzy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值