Answer
Iterator and ListIterator in Java
Iterator — Forward Traversal Only
Java
import java.util.*;
public class IteratorDemo {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>(
Arrays.asList("Selenium", "TestNG", "Cucumber", "Maven", "Jenkins")
);
// Get Iterator
Iterator<String> it = list.iterator();
System.out.println("Using Iterator (forward):");
while (it.hasNext()) {
String tool = it.next();
System.out.println(tool);
// Safe removal during iteration (avoids ConcurrentModificationException)
if (tool.equals("Maven")) {
it.remove(); // removes "Maven" safely
}
}
System.out.println("After removing Maven: " + list);
}
}
Output
CODE
Using Iterator (forward):
Selenium
TestNG
Cucumber
Maven
Jenkins
After removing Maven: [Selenium, TestNG, Cucumber, Jenkins]
ListIterator — Bidirectional + Modify
Java
ArrayList<String> list = new ArrayList<>(
Arrays.asList("Chrome", "Firefox", "Edge", "Safari")
);
ListIterator<String> lit = list.listIterator();
// Forward traversal
System.out.println("Forward:");
while (lit.hasNext()) {
System.out.println(lit.nextIndex() + ": " + lit.next());
}
// Backward traversal
System.out.println("Backward:");
while (lit.hasPrevious()) {
System.out.println(lit.previousIndex() + ": " + lit.previous());
}
// Modify during iteration
ListIterator<String> lit2 = list.listIterator();
while (lit2.hasNext()) {
String browser = lit2.next();
lit2.set(browser + "-Driver"); // replace each element
}
System.out.println("Modified: " + list);
// → [Chrome-Driver, Firefox-Driver, Edge-Driver, Safari-Driver]
Iterator vs ListIterator vs For-Each
| Feature | Iterator | ListIterator | For-Each |
|---|---|---|---|
| Direction | Forward only | Both | Forward only |
| Remove during loop | Yes (it.remove()) | Yes | NO (ConcurrentModificationException) |
| Add during loop | No | Yes (lit.add()) | No |
| Index access | No | Yes | No |
| Works on | Any Collection | List only | Any Iterable |
Automation Testing Relevance
Java
// Safely remove stale elements from list
List<WebElement> elements = driver.findElements(By.css(".item"));
Iterator<WebElement> it = elements.iterator();
while (it.hasNext()) {
WebElement el = it.next();
if (!el.isDisplayed()) {
it.remove(); // remove elements that are not visible
}
}
