Removing items from a list [duplicate]
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.
You need to use Iterator
and call remove()
on iterator
instead of using for
loop.
You cannot do it because you are already looping on it.
Inorder to avoid this situation use Iterator,which guarentees you to remove the element from list safely ...
List<Object> objs;
Iterator<Object> i = objs.iterator();
while (i.hasNext()) {
Object o = i.next();
//some condition
i.remove();
}
You can't and shouldn't modify a list while iterating over it. You can solve this by temporarely saving the objects to remove:
List<Object> toRemove = new ArrayList<Object>();
for(Object a: list){
if(a.getXXX().equalsIgnoreCase("AAA")){
toRemove.add(a);
}
}
list.removeAll(toRemove);