Java中如何正确遍历并删除集合元素?
请说明Java中遍历集合时安全删除元素的几种方式,包括:使用Iterator.remove()、使用for-each导致的ConcurrentModificationException原因、Java 8的removeIf(),以及for循环倒序遍历。
回答
专业代码师
错误方式:for-each循环中调用集合的remove()
List<String> list = new ArrayList<>(Arrays.asList("a","b","c"));
for (String s : list) {
if ("a".equals(s)) list.remove(s); // ❌ ConcurrentModificationException
}
原因:for-each编译为Iterator迭代,迭代器维护expectedModCount,集合的remove()会修改modCount,导致modCount != expectedModCount,抛出异常。
正确方式:
- Iterator.remove():
Iterator<String> it = list.iterator();
while (it.hasNext()) {
if ("a".equals(it.next())) it.remove();
}
- Java 8 removeIf()(推荐,底层也是Iterator):
list.removeIf(s -> "a".equals(s));
- for循环倒序遍历(适用于List):
for (int i = list.size() - 1; i >= 0; i--) {
if ("a".equals(list.get(i))) list.remove(i);
}
- 创建新集合:
List<String> result = list.stream().filter(s -> !"a".equals(s)).collect(Collectors.toList());
注意:LinkedList使用index遍历时remove(i)是O(n)操作,效率低。推荐removeIf()或Iterator。