You can't remove an item from a collection you're iterating over except using Iterator.remove - you'll get a ConcurrentModificationException
. So your loop would be something like:
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
String value = iterator.next();
if (value.equals("B")) {
iterator.remove();
}
}
Of course, you should use removeAll
to just remove all items with a specific value - but the above approach is the one to use if you need to remove based on some condition other than simple equality (e.g. "remove all values with a length greater than 5". Another option is to collect all the values to remove in a new collection, and then call removeAll
afterwards.