在遍历列表时,我想根据条件删除列表中的一项。请参阅下面的代码。
这给了我一个 ConcurrentModification
异常。
for (Object a : list) {
if (a.getXXX().equalsIgnoreCase("AAA")) {
logger.info("this is AAA........should be removed from the list ");
list.remove(a);
}
}
如何做到这一点?
最佳答案
for (Iterator<String> iter = list.listIterator(); iter.hasNext(); ) {
String a = iter.next();
if (...) {
iter.remove();
}
}
另外假设列表是字符串。
正如已经回答的那样,需要一个 list.iterator()
。 listIterator也可以做一些导航。
----------
更新
正如@AyushiJain 评论的那样,有
list.removeIf(...);
关于java - 从列表中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17279519/