Get the iterator() from a collection
Iterator<E> iterator()
- Returns an iterator over the elements in this collection.
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
Collection aList = new ArrayList();
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
aList.add("java2 s .com");
System.out.println("ArrayList: ");
System.out.println(aList);
Iterator itr = aList.iterator();
String strElement = "";
while (itr.hasNext()) {
strElement = (String) itr.next();
if (strElement.equals("2")) {
itr.remove();
break;
}
}
System.out.println("ArrayList after removal : ");
System.out.println(aList);
}
}
The output:
ArrayList:
[1, 2, 3, 4, java2 s .com]
ArrayList after removal :
[1, 3, 4, java2 s .com]