如何从对象列表中删除几个对象
How to remove few objects from a List of Object
假设我有一个 Employee 对象列表,每个 Employee Class 都有 employeeName、employeeAddress、salary 等属性。现在我必须删除名称为 "John" 和 Salary 的 Employee 对象> 40000。
List empList = new ArrayList<>();
// 将数百万名员工添加到 empList。
根据我的理解,要删除具有上述条件的员工,我应该使用以下代码:
Iterator<Employee> iterator = list.iterator();
while (iterator.hasNext()) {
Employee employee = iterator.next();
if ("John".equals(employee.getName) && employee.getSalary>40000) {
iterator .remove();
}
}
所以基本上上面的代码将从列表中删除所需的 Employee 对象。
如果我的理解正确,请告诉我。
除此之外,请澄清以下内容:
1. 当我们有数百万条记录时,我们将如何解决这个问题。
2、iterator.remove()和list.remove()
的区别
提前致谢。
一次加载数百万个对象并不好。你如何获得所有这些记录?如果您从数据库中读取它们,最好使用 SQL 进行过滤。
where e.name = "John" and e.salary > 40000
如果你从一个文件中读取它们,你不应该一次读取它们,数据库也是如此。您可以将记录提取到批量,比如说 1000。
如果你像上面那样实现它,你也可以使用流:
List<Employee> filteredList = list.stream()
.filter(employee -> employee.getName().equals("John"))
.filter(employee.getSlaray() > 40000)
.collect(Collectors.toList());
然后您可以得到 1000 行的筛选列表并将它们分开处理。
1) 如果你想让对象保持活动状态,你可以只过滤需要的对象
list.stream()
.filter(emp->"John".equals(emp.getName()) && emp.getSlaray() >40000)
.collect(Collectors.toList());
2) 如果您正在遍历集合并使用:
Collection.remove()
引发特定的 ConcurrentModifcationException 原因,该异常导致更改先前用于构造完成循环所需的显式调用系列的对象的状态,但是当您使用
Iterator.remove()
您更改基础集合并重新评估完成循环所需的显式调用系列。
假设我有一个 Employee 对象列表,每个 Employee Class 都有 employeeName、employeeAddress、salary 等属性。现在我必须删除名称为 "John" 和 Salary 的 Employee 对象> 40000。
List empList = new ArrayList<>(); // 将数百万名员工添加到 empList。
根据我的理解,要删除具有上述条件的员工,我应该使用以下代码:
Iterator<Employee> iterator = list.iterator();
while (iterator.hasNext()) {
Employee employee = iterator.next();
if ("John".equals(employee.getName) && employee.getSalary>40000) {
iterator .remove();
}
}
所以基本上上面的代码将从列表中删除所需的 Employee 对象。 如果我的理解正确,请告诉我。
除此之外,请澄清以下内容: 1. 当我们有数百万条记录时,我们将如何解决这个问题。 2、iterator.remove()和list.remove()
的区别提前致谢。
一次加载数百万个对象并不好。你如何获得所有这些记录?如果您从数据库中读取它们,最好使用 SQL 进行过滤。
where e.name = "John" and e.salary > 40000
如果你从一个文件中读取它们,你不应该一次读取它们,数据库也是如此。您可以将记录提取到批量,比如说 1000。
如果你像上面那样实现它,你也可以使用流:
List<Employee> filteredList = list.stream()
.filter(employee -> employee.getName().equals("John"))
.filter(employee.getSlaray() > 40000)
.collect(Collectors.toList());
然后您可以得到 1000 行的筛选列表并将它们分开处理。
1) 如果你想让对象保持活动状态,你可以只过滤需要的对象
list.stream()
.filter(emp->"John".equals(emp.getName()) && emp.getSlaray() >40000)
.collect(Collectors.toList());
2) 如果您正在遍历集合并使用:
Collection.remove()
引发特定的 ConcurrentModifcationException 原因,该异常导致更改先前用于构造完成循环所需的显式调用系列的对象的状态,但是当您使用
Iterator.remove()
您更改基础集合并重新评估完成循环所需的显式调用系列。