While looping through a list, I would like to remove an item of a list depending on a condition. See the code below.
This gives me a ConcurrentModification
exception.
for (Object a : list) {
if (a.getXXX().equalsIgnoreCase("AAA")) {
logger.info("this is AAA........should be removed from the list ");
list.remove(a);
}
}
How can this be done?
for (Iterator<String> iter = list.listIterator(); iter.hasNext(); ) {
String a = iter.next();
if (...) {
iter.remove();
}
}
Making an additional assumption that the list is of strings.
As already answered, an list.iterator()
is needed. The listIterator can do a bit of navigation too.