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]
Related Articles:
- Java – Conversion of Arrays to List
- Java – Conversion of Arrays to List in Java 8
- Java – Conversion of ArrayList to Arrays in 2 ways
- Java – Conversion of Arrays to Vector
- Java – Conversion of Arrays to HashSet
- Java – Conversion of HashSet to Arrays
- Java – Conversion of LinkedList into Vector
- Java – Conversion of ArrayList into HashSet to remove duplicate elements
- Java – How to convert LinkedList to contain unique elements in ascending-order ?
- Java – Converting Ordered ArrayList into Sorted TreeSet
- Java – Conversion of Map to List
- Java 8 – Conversion of Map to List
- Java – Conversion of List to Map
- Java 8 – Conversion of List to Map
- Java – How to remove elements while iterating collection object ?
References:
- https://docs.oracle.com/javase/tutorial/collections/intro/
- https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
- https://docs.oracle.com/javase/tutorial/collections/interfaces/list.html
- https://docs.oracle.com/javase/7/docs/api/java/util/List.html
- https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html
- https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
- https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
Happy Coding !!
Happy Learning !!