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 < > ();
  names.add("abc");
  names.add("mnc");
  names.add("xyz");

//for loop will throw ConcurrentModificationException
   for (String name: names) {
    if (name.startsWith("a")) {
     System.out.println("name is " + name);
     names.remove(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 = iter.next();
    if (name.startsWith("a")) {
     iter.remove();
    }
   }
   System.out.println("names size is =" + names.size());

 }

}

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