How to remove elements while iterating collection object

In this article, we will discuss how to remove elements from ArrayList while iterating Collections objects using Iterator interface

Note: ConcurrentModificationException will be thrown when one thread is iterating and other thread is trying to modify ArrayList contents (i.e.; add or remove)

 

Removing elements from ArrayList using remove() method of Iterator interface :

DeleteElementFromArrayListWhileIterating.java

package in.bench.resources.java.collections;

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

public class DeleteElementFromArrayListWhileIterating {

	public static void main(String[] args) {

		// creating ArrayList object of type String
		ArrayList<String> actress = new ArrayList<String>();

		// adding elements to ArrayList object
		actress.add("Nayantara");
		actress.add("Anushka");
		actress.add("Samantha");
		actress.add("Namitha");
		actress.add("Ileana");

		// printing before remove() operation
		System.out.println("Elements of AL : " 
				+ actress);

		// Iterating using Iterator interface
		Iterator<String> itr = actress.iterator();
		while(itr.hasNext()) {

			if(itr.next().equalsIgnoreCase("Anushka")) {
				itr.remove();
			}
		}

		// printing after remove() operation
		System.out.println("\n\nAfter removal of elements of AL :" 
				+ actress);
	}
}

Output:

Elements of AL : [Nayantara, Anushka, Samantha, Namitha, Ileana]


After removal of elements of AL :[Nayantara, Samantha, Namitha, Ileana]

 

References:

 

Happy Coding !!
Happy Learning !!

How to get all keys of a HashMap
How to get minimum element from ArrayList