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?

aioobe
  • 399,198
  • 105
  • 792
  • 807
hrishikeshp19
  • 8,288
  • 23
  • 75
  • 139

2 Answers2

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();
}
aioobe
  • 399,198
  • 105
  • 792
  • 807
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();
    }
}
Eran
  • 374,785
  • 51
  • 663
  • 734