Java iterator for avoiding concurrent modification exception.

Sometime we need to remove certain set of items from the collection of items based on certain condition.

But the major problem which comes into picture is while iterating and simultaneously removing item from a collection.

Let look into a example program and it’s behaviour.

import java.util.*;

class ConcurrentModification {

 public static void main(String args[]) {

  List < String > names = new ArrayList < > ();

//for loop will throw ConcurrentModificationException
   for (String name: names) {
    if (name.startsWith("a")) {
     System.out.println("name is " + name);
   System.out.println("names size is =" + names.size());

// comment out the above for loop and use this iterator for removing items based on certain condition 
  Iterator < String > iter = names.iterator();
   while (iter.hasNext()) {
    String name =;
    if (name.startsWith("a")) {
   System.out.println("names size is =" + names.size());



In the above code using iterator we can remove item while iterating through the list.