This example will explain how to remove an element from ArrayList using Iterator’s remove method in Java.
Source Code
package com.beginner.examples;
import java.util.ArrayList;
import java.util.Iterator;
public class RemoveElementThroughIterator {
public static void main(String[] args) {
//create ArrayList.
ArrayList arrayList = new ArrayList();
arrayList.add("A");
arrayList.add("B");
arrayList.add("C");
arrayList.add("D");
System.out.println("Before removal, ArrayList contains : ");
for(int i=0; i< arrayList.size(); i++) {
System.out.println(arrayList.get(i));
}
/*
* remove 2 from ArrayList using Iterator's remove method.
*/
Iterator iterator = arrayList.iterator();
String stringTmp = null;
while(iterator.hasNext()) {
stringTmp = (String)iterator.next();
if(stringTmp.equals("C")) {
iterator.remove();
break;
}
}
System.out.println("After removal, ArrayList contains : ");
for(int i=0; i< arrayList.size(); i++) {
System.out.println(arrayList.get(i));
}
}
}
Output:
Before removal, ArrayList contains :
A
B
C
D
After removal, ArrayList contains :
A
B
D
References
Imported packages in Java documentation: