Java – How to add/remove/modify an element in List while iterating ?

In this article, we will discuss and learn with different illustrations on how to add/remove an element to List/ArrayList while iterating

First, we will understand what happens when we are iterating and modifying the List/ArrayList at the same time

1. Modifying original List throws CMEx :

While iterating List/ArrayList, if we try to modify original List like adding/removing elements then program throws ConcurrentModificationException. We will try this with 3 different loops as mentioned below,

  1. Using forEach loop from Java 1.5 version
  2. Using Iterator interface from Java 1.2 version
  3. Using ListIterator interface from Java 1.2 version

1.1 Using forEach loop

  • Here, we are trying to remove elements while iterating List using forEach loop which throws ConcurrentModificationException

AddRemoveWhileIteratingUsingForEachLoop.java

package in.bench.resources.listiterator;

import java.util.ArrayList;

public class AddRemoveWhileIteratingUsingForEachLoop {

	public static void main(String[] args) {

		// Fruits list
		ArrayList<String> fruits = new ArrayList<String>();
		fruits.add("Melons");
		fruits.add("Mango");
		fruits.add("Apple");
		fruits.add("Cherry");
		fruits.add("Grapes");


		// print to console
		System.out.println("Original Fruit List :- \n" + fruits + "\n\n");


		// iterate List elements using forEach loop
		for(String fruit : fruits) {

			// try to remove from original List
			fruits.remove(fruit);
		}


		// print to console
		System.out.println("\nAfter removal of Melons & addition of Banana :- \n"
				+ fruits);
	}
}

Output:

Original Fruit List :- 
[Melons, Mango, Apple, Cherry, Grapes]


Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1013)
	at java.base/java.util.ArrayList$Itr.next(ArrayList.java:967)
	at in.bench.resources.listiterator.AddRemoveWhileIteratingUsingForEachLoop
.main(AddRemoveWhileIteratingUsingForEachLoop.java:23)

1.2 Using Iterator

  • Here, we are trying to remove an element while iterating List using Iterator interface which also throws ConcurrentModificationException
  • Iterator has 2 useful methods namely,
    1. hasNext() method – allows to check whether there are any elements present in the List
    2. next() method – used to get next element if there are elements present in the List

RemoveElementWhileIteratingUsingIterator2.java

package in.bench.resources.listiterator;

import java.util.ArrayList;
import java.util.Iterator;

public class RemoveElementWhileIteratingUsingIterator2 {

	public static void main(String[] args) {

		// Fruits list
		ArrayList<String> fruits = new ArrayList<String>();
		fruits.add("Melons");
		fruits.add("Mango");
		fruits.add("Apple");
		fruits.add("Cherry");
		fruits.add("Grapes");


		// print to console
		System.out.println("Original Fruit List :- \n" + fruits + "\n\n");


		// get Iterator
		Iterator<String> iterator = fruits.iterator();


		// iterate using Iterator
		while(iterator.hasNext()) {

			// try to add/remove from original List
			if(iterator.next().equalsIgnoreCase("Melons")) {
				fruits.remove("Melons");
			}
		}


		// print to console
		System.out.println("\nAfter removal of Cherry :- \n" + fruits);
	}
}

Output:

Original Fruit List :- 
[Melons, Mango, Apple, Cherry, Grapes]


Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1013)
	at java.base/java.util.ArrayList$Itr.next(ArrayList.java:967)
	at in.bench.resources.listiterator.RemoveElementWhileIteratingUsingIterator2
.main(RemoveElementWhileIteratingUsingIterator2.java:31)

1.3 Using ListIterator

  • Here, we are trying to add an element while iterating List using ListIterator interface which also throws ConcurrentModificationException
  • Like Iterator, ListIterator also has 2 useful methods namely,
    1. hasNext() method – allows to check whether there are any elements present in the List
    2. next() method – used to get next element if there are elements present in the List

AddRemoveWhileIteratingThrowsCMEx.java

package in.bench.resources.listiterator;

import java.util.ArrayList;
import java.util.ListIterator;

public class AddRemoveWhileIteratingThrowsCMEx {

	public static void main(String[] args) {

		// Fruits list
		ArrayList<String> fruits = new ArrayList<String>();
		fruits.add("Melons");
		fruits.add("Mango");
		fruits.add("Apple");
		fruits.add("Cherry");
		fruits.add("Grapes");


		// print to console
		System.out.println("Original Fruit List :- \n" + fruits + "\n\n");


		// iterate using Iterator
		ListIterator<String> listIterator = fruits.listIterator();


		// Forward Iterating
		while(listIterator.hasNext()) {

			if(listIterator.next().equalsIgnoreCase("Grapes")) {

				// trying to add element to Original list
				fruits.add("Banana");
			}
		}


		// print to console
		System.out.println("\nAfter removal of Cherry & addition of Banana :- \n"
				+ fruits);
	}
}

Output:

Original Fruit List :- 
[Melons, Mango, Apple, Cherry, Grapes]


Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1013)
	at java.base/java.util.ArrayList$Itr.next(ArrayList.java:967)
	at in.bench.resources.listiterator.AddRemoveWhileIteratingThrowsCMEx
.main(AddRemoveWhileIteratingThrowsCMEx.java:30)

2. Adding/removing elements to/from List :

Iterating using Iterator/ListIterator allows to add/remove element and these modification (add/remove) is reflected in the original List. We will see 2 different examples using Iterator and ListIterator,

  1. Remove element using Iterator interface
  2. Add/Remove element using ListIterator interface

2.1 Remove element using Iterator interface

  • Using Iterator, we can only remove element from iterating List using remove() method
  • But there should be some operations involving obtained iterator otherwise program throws java.lang.IllegalStateException
  • Note:- use remove() method of Iterator interface for removing elements from iterating List otherwise modifying original List still throws ConcurrentModificationException as shown in the above example 1.2

RemoveElementWhileIteratingUsingIterator.java

package in.bench.resources.listiterator;

import java.util.ArrayList;
import java.util.Iterator;

public class RemoveElementWhileIteratingUsingIterator {

	public static void main(String[] args) {

		// Fruits list
		ArrayList<String> fruits = new ArrayList<String>();
		fruits.add("Melons");
		fruits.add("Mango");
		fruits.add("Apple");
		fruits.add("Cherry");
		fruits.add("Grapes");


		// print to console
		System.out.println("Original Fruit List :- \n" + fruits);


		// get Iterator
		Iterator<String> iterator = fruits.iterator();


		// iterate
		while(iterator.hasNext()) {

			if(iterator.next().equalsIgnoreCase("Cherry")) 
				iterator.remove();
		}


		// print to console
		System.out.println("\nAfter removal of Cherry :- \n" + fruits);
	}
}

Output:

Original Fruit List :- 
[Melons, Mango, Apple, Cherry, Grapes]

After removal of Cherry :- 
[Melons, Mango, Apple, Grapes]

2.2 Add/Remove element using ListIterator interface

  • Like Iterator, ListIterator needs some operations involving obtained listIterator otherwise program throws java.lang.IllegalStateException
  • Unlike Iterator, ListIterator has methods to add/remove elements from iterating List using add() and remove() methods respectively
  • Note:- use add() or remove() methods of ListIterator interface for adding or removing elements from iterating List respectively otherwise modifying original List still throws ConcurrentModificationException as shown above example 1.3

AddRemoveWhileIteratingUsingListIterator.java

package in.bench.resources.listiterator;

import java.util.ArrayList;
import java.util.ListIterator;

public class AddRemoveWhileIteratingUsingListIterator {

	public static void main(String[] args) {

		// Fruits list
		ArrayList<String> fruits = new ArrayList<String>();
		fruits.add("Melons");
		fruits.add("Mango");
		fruits.add("Apple");
		fruits.add("Cherry");
		fruits.add("Grapes");


		// print to console
		System.out.println("Original Fruit List :- \n" + fruits);


		// iterate using Iterator
		ListIterator<String> listIterator = fruits.listIterator();


		// forward iterating
		while(listIterator.hasNext()) {

			if(listIterator.next().equalsIgnoreCase("Melons")) {

				// replace = remove Melons + add Banana
				listIterator.remove();
				listIterator.add("Banana");
			}
		}


		// print to console
		System.out.println("\nAfter removal of Melons & addition of Banana :- \n" + fruits);
	}
}

Output:

Original Fruit List :- 
[Melons, Mango, Apple, Cherry, Grapes]

After removal of Melons & addition of Banana :- 
[Banana, Mango, Apple, Cherry, Grapes]

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to check whether a number exists in an Arrays or List or Stream ?
Java 8 - How to merge/concatenate/join two lists into single list ?