Can we remove elements from ArrayList while iterating?

Use Iterator to remove an element from a Collection in Java

Java 8Object Oriented ProgrammingProgramming

An element can be removed from a Collection using the Iterator method remove(). This method removes the current element in the Collection. If the remove() method is not preceded by the next() method, then the exception IllegalStateException is thrown.

A program that demonstrates this is given as follows.

Example

Live Demo

import java.util.ArrayList; import java.util.Iterator; public class Demo { public static void main(String[] args) { ArrayList aList = new ArrayList(); aList.add("Apple"); aList.add("Mango"); aList.add("Guava"); aList.add("Orange"); aList.add("Peach"); System.out.println("The ArrayList elements are: "); for (String s: aList) { System.out.println(s); } Iterator i = aList.iterator(); String str = ""; while (i.hasNext()) { str = (String) i.next(); if (str.equals("Orange")) { i.remove(); System.out.println("\nThe element Orange is removed"); break; } } System.out.println("\nThe ArrayList elements are: "); for (String s: aList) { System.out.println(s); } } }

Output

The output of the above program is as follows

The ArrayList elements are: Apple Mango Guava Orange Peach The element Orange is removed The ArrayList elements are: Apple Mango Guava Peach
Can we remove elements from ArrayList while iterating?
Arjun Thakur
Published on 18-Jan-2019 06:08:12
Previous Page Print Page
Next Page
Advertisements