Removing items from a list

Techie picture Techie · Jun 24, 2013 · Viewed 348.5k times · Source

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?

Answer

Joop Eggen picture Joop Eggen · Jun 24, 2013
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.