过滤两个list集合中间的重复元素
程序员文章站
2022-03-04 18:53:34
...
注:整理自如何使用Java List等集合类的removeAll方法和Java中找到两个list中的不同元素
- 使用 boolean removeAll(Collection<?> c)方法,从列表中移除指定 collection 中包含的其所有元素(可选操作)。
- 执行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;
}
上一篇: Eclipse开发工具