java - 如何通过比较两个列表从一个列表中删除元素
问题描述
我有两个列表,比如 List1 和 List2。如果 List1 中已经存在,我需要从 List2 中删除元素
为避免 ConCurrentModificationException,我尝试使用 ListIterator
employeeList1 // data present
employeeList2 // data present
ListIterator<Employee> zeroList=employeeList2.listIterator();
//remove employee if already present in list1
while(zeroList.hasNext()){
for(Employee employee : employeeList1){
if(zeroList.next().getID().equals(employee.getId())){
zeroList.remove();
}
}
}
我在 if 条件中得到以下异常
java.util.NoSuchElementException
List1 中可能不存在该元素,但检查条件是必要的。
解决方案
您可以removeAll
在要从中删除元素的集合上使用方法,并将集合作为包含要删除的元素的参数传递。
List<String> list1 = new ArrayList<>();
list1.add("a");
list1.add("b");
list1.add("c");
List<String> list2 = new ArrayList<>();
list2.add("a");
list2.add("p");
list2.add("q");
list2.removeAll(list1);
System.out.println(list2);
从 list2 中删除a
,因为它存在于 list1 中并p
仅q
打印,
[p, q]
编辑:这是一个Employee
类的示例代码,而你的可能是不同的,但正如你所说,你的关键是employeeId
因此equals
,hashCode
方法只需要发挥作用employeeId
。
static class Employee {
private long employeeId;
private String name;
// whatever more variables
public Employee(long employeeId, String name) {
this.employeeId = employeeId;
this.name = name;
}
public String toString() {
return String.format("Employee[employeeId=%s, name=%s]", employeeId, name);
}
@Override
public boolean equals(Object o) {
if (o instanceof Employee) {
return this.employeeId == ((Employee) o).employeeId;
}
return false;
}
@Override
public int hashCode() {
return new Long(employeeId).hashCode();
}
}
public static void main(String[] args) throws Exception {
List<Employee> list1 = new ArrayList<>();
list1.add(new Employee(1, "a"));
list1.add(new Employee(2, "b"));
list1.add(new Employee(3, "c"));
List<Employee> list2 = new ArrayList<>();
list2.add(new Employee(1, "a"));
list2.add(new Employee(4, "d"));
list2.add(new Employee(5, "e"));
list2.removeAll(list1);
System.out.println(list2);
}
尝试使用此代码并查看它打印的内容,然后只评论两者equals
和hashCode
方法,然后看看会发生什么。在您评论这两个方法后,list1 中存在的对象将不会被删除,因为 list 不知道两个对象何时相等。
推荐阅读
- android - 使用 Hilt 注入 viewModel 时不调用 init
- python - 不同维度矩阵的二项式公式实现
- python - 来自 scipy.optimize 的曲线拟合不起作用
- python - 在编辑预订django上使编辑功能没有冲突
- c - 读取未初始化的 malloc() 内存会调用未定义的行为吗?
- javascript - 从另一个模块的异步回调函数返回的值未定义
- flutter - 如何在 Cupertino TextField 中显示错误标签
- sql - 如何在两个数字之间选择未占用的范围
- excel - 使用 Excel VBA 检索 Outlook 电子邮件数据
- javascript - 在 Chrome 扩展 JavaScript 中获取 YouTube 帐户名称