1

I have Java ArrayList<Map<String, Object>>. Is it okay to remove elements from that list as follows:

    for (Map<String, Object> anObject : manyObjects) {
        if (anObject.get("x").equals("y")) {
            manyObjects.remove(anObject);
        }
    }

Is there anything fundamentally wrong with this approach?

2

2 Answers 2

2

No, you can't make structural modifications to the list (such as removing elements from it) while iterating over it using an enhanced for loop. That would (most likely) end up in a ConcurrentModificationException.

Here's a better way using the stream API:

manyObjects.removeIf(map -> map.get("x").equals("y"));

The "old" (pre Java 8) way is to use an iterator and the remove() method as follows:

Iterator<Map<String, Object>> iter = manyObjects.iterator();
while (iter.hasNext()) {
    if (iter.next().get("x").equals("y"))
        iter.remove();
}
1

You can't removes elements from a List while iterating over it with the enhanced for loop, since it will throw a CuncurrentModificationException. You can use an explicit iterator instead :

Iterator<Map<String, Object>> iter = manyObjects.iterator();
while (iter.hasNext()) {
    Map<String, Object> anObject = iter.next();
    if (anObject.get("x").equals("y")) {
        iter.remove();
    }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.