Notice that this may only happen intermittently because we are calling remove() inside a conditional statement. So the exception will be thrown whenever we have a String that starts with "A" in our list.

Solutions

There are a number of ways to prevent ConcurrentModificationException, and we'll explore these below.

Use an Iterator

We can change how we iterate by replacing the enhanced for-loop with a while loop that uses an Iterator object. The Iterator allows us to safely remove the matching element because we are not calling remove() directly on the list object.

Code