Java · Collections · Topic 6
Iterators
Traverse and safely modify Java collections using Iterator, ListIterator, Enumeration, loops, and forEach().
Step 1 of 18
6.1 Introduction to Iteration
Define iteration and identify Java traversal mechanisms.
If a list contains Java, Python, and Database, iteration processes Java, then Python, then Database.
Traversal mechanisms
- Iterator
- ListIterator
- Enumeration
- Enhanced for loop
- Traditional indexed for loop
- forEach()
Check your understanding: What does iteration do?
It visits and processes collection elements one by one.
Step 2 of 18
6.2 Iterator Interface
Obtain an Iterator and use its four principal methods.
Iterator<String> iterator = names.iterator();| Method | Description |
|---|---|
| hasNext() | Checks whether another element is available |
| next() | Returns the next element |
| remove() | Removes the last element returned by next() |
| forEachRemaining() | Processes all remaining elements |
Check your understanding: Which method checks whether another element is available?
hasNext().
Step 3 of 18
6.3 Traversing with Iterator
Trace the iterator traversal cycle in a complete program.
import java.util.ArrayList;
import java.util.Iterator;
public class IteratorDemo {
public static void main(String[] args) {
ArrayList<String> subjects = new ArrayList<>();
subjects.add("Java");
subjects.add("Python");
subjects.add("Database");
Iterator<String> iterator = subjects.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}Java
Python
DatabaseWorking process
- iterator() creates the iterator
- hasNext() checks availability
- next() returns the element
- The cycle repeats until traversal ends
Check your understanding: What is printed first by the example?
Java.
Step 4 of 18
6.4 Removing Elements Using Iterator
Remove matching elements safely during traversal.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
public class IteratorRemoveDemo {
public static void main(String[] args) {
ArrayList<Integer> numbers =
new ArrayList<>(Arrays.asList(10, 15, 20, 25));
Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
int number = iterator.next();
if (number % 2 != 0) iterator.remove();
}
System.out.println(numbers);
}
}[10, 20]Check your understanding: Which values remain after removing odd numbers from 10, 15, 20, 25?
10 and 20.
Step 5 of 18
6.5 Concurrent Modification Problem
Distinguish direct structural modification from iterator-controlled removal.
while (iterator.hasNext()) {
String name = iterator.next();
if (name.equals("Amit")) names.remove(name); // unsafe
}while (iterator.hasNext()) {
String name = iterator.next();
if (name.equals("Amit")) iterator.remove();
}Check your understanding: Does concurrent modification necessarily mean multiple threads?
No. Direct structural modification during iteration can cause it in a single thread.
Step 6 of 18
6.6 Limitations of Iterator
Identify when Iterator is insufficient.
Iterator limitations
- Forward traversal only
- No index information
- Cannot add elements
- Cannot directly replace elements
- Can remove through remove()
Check your understanding: Which iterator should be selected for backward list traversal?
ListIterator.
Step 7 of 18
6.7 ListIterator Interface
Explain the list-specific capabilities of ListIterator.
ListIterator<String> iterator = names.listIterator();Capabilities
- Forward and backward traversal
- Add and remove elements
- Replace elements
- Read next and previous indexes
Supported examples
- ArrayList
- LinkedList
- Vector
- Stack
Check your understanding: Can ListIterator be obtained directly from a Set?
No. It is designed for List implementations.
Step 8 of 18
6.8 Important ListIterator Methods
Match bidirectional and modification operations with ListIterator methods.
| Method | Description |
|---|---|
| hasNext() | Checks for a next element |
| next() | Returns the next element |
| hasPrevious() | Checks for a previous element |
| previous() | Returns the previous element |
| nextIndex() | Index of the next element |
| previousIndex() | Index of the previous element |
| add(element) | Inserts an element |
| remove() | Removes the current element |
| set(element) | Replaces the current element |
Check your understanding: Which method returns the preceding element?
previous().
Step 9 of 18
6.9 Forward and Backward Traversal
Move a ListIterator to the end and traverse back to the beginning.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.ListIterator;
public class ListIteratorDemo {
public static void main(String[] args) {
ArrayList<String> subjects =
new ArrayList<>(Arrays.asList("Java", "Python", "Database"));
ListIterator<String> iterator = subjects.listIterator();
System.out.println("Forward traversal:");
while (iterator.hasNext()) System.out.println(iterator.next());
System.out.println("Backward traversal:");
while (iterator.hasPrevious()) System.out.println(iterator.previous());
}
}Forward traversal:
Java
Python
Database
Backward traversal:
Database
Python
JavaListIterator<String> iterator = subjects.listIterator(subjects.size());Check your understanding: What is the first value printed during backward traversal?
Database.
Step 10 of 18
6.10 Modifying a List Using ListIterator
Insert and replace values during traversal.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.ListIterator;
public class ListIteratorModifyDemo {
public static void main(String[] args) {
ArrayList<String> subjects =
new ArrayList<>(Arrays.asList("Java", "Python", "Database"));
ListIterator<String> iterator = subjects.listIterator();
while (iterator.hasNext()) {
String subject = iterator.next();
if (subject.equals("Python")) iterator.set("Advanced Python");
if (subject.equals("Java")) iterator.add("Advanced Java");
}
System.out.println(subjects);
}
}[Java, Advanced Java, Advanced Python, Database]Check your understanding: Which method replaces Python with Advanced Python?
set().
Step 11 of 18
6.11 Difference Between Iterator and ListIterator
Compare scope, direction, modification, indexes, and creation methods.
| Iterator | ListIterator |
|---|---|
| Works with most collections | Works only with lists |
| Traverses forward | Traverses forward and backward |
| Can remove | Can add, remove, and replace |
| No index information | Provides next and previous indexes |
| Created by iterator() | Created by listIterator() |
Check your understanding: Which one provides nextIndex() and previousIndex()?
ListIterator.
Step 12 of 18
6.12 Enumeration Interface
Traverse legacy collections with Enumeration.
| Method | Description |
|---|---|
| hasMoreElements() | Checks whether another element exists |
| nextElement() | Returns the next element |
import java.util.Enumeration;
import java.util.Vector;
public class EnumerationDemo {
public static void main(String[] args) {
Vector<String> subjects = new Vector<>();
subjects.add("Java"); subjects.add("Python"); subjects.add("Database");
Enumeration<String> enumeration = subjects.elements();
while (enumeration.hasMoreElements()) {
System.out.println(enumeration.nextElement());
}
}
}Java
Python
DatabaseCheck your understanding: Which method returns the next Enumeration element?
nextElement().
Step 13 of 18
6.13 Iterator versus Enumeration
Contrast modern Iterator behavior with legacy Enumeration.
| Iterator | Enumeration |
|---|---|
| Modern interface | Legacy interface |
| Most modern collections | Mainly legacy classes |
| hasNext() | hasMoreElements() |
| next() | nextElement() |
| Supports removal | No removal |
| Can be fail-fast | Usually not fail-fast |
Check your understanding: Which cursor supports remove()?
Iterator.
Step 14 of 18
6.14 Enhanced For Loop
Use enhanced for for clear read-only traversal of arrays and Iterable collections.
for (String subject : subjects) {
System.out.println(subject);
}Advantages
- Simple and readable
- No index management
- Works with arrays and most collections
Limitations
- No direct index
- Forward traversal
- Do not directly remove during traversal
- Less modification control than ListIterator
Check your understanding: Does enhanced for directly provide an index?
No.
Step 15 of 18
6.15 Traditional For Loop
Use indexed traversal where position matters.
for (int i = 0; i < subjects.size(); i++) {
System.out.println(i + " : " + subjects.get(i));
}Use it when
- The index is required
- Elements must be accessed or updated by position
- The collection implements List
Check your understanding: Why is this loop unsuitable for Set?
Set does not provide index-based access.
Step 16 of 18
6.16 forEach Method
Process collection elements with a lambda or method reference.
subjects.forEach(subject -> System.out.println(subject));subjects.forEach(System.out::println);Check your understanding: What method reference prints every element?
System.out::println.
Step 17 of 18
6.17 Traversal Method Comparison
Compare traversal direction, modification support, and suitable structures.
| Method | Direction | Modification | Suitable for |
|---|---|---|---|
| Iterator | Forward | Remove | Most collections |
| ListIterator | Both | Add, remove, replace | Lists |
| Enumeration | Forward | None | Legacy classes |
| Enhanced for | Forward | Normally read-only | Arrays and collections |
| Traditional for | Either by index | Index-based | Lists |
| forEach() | Forward processing | Normally processing | Modern code |
Check your understanding: Which method supports bidirectional traversal and replacement?
ListIterator.
Step 18 of 18
6.18 Selection Guide
Select a traversal mechanism for a concrete requirement.
| Requirement | Recommended choice |
|---|---|
| Simple read-only traversal | Enhanced for |
| Safe removal while traversing | Iterator |
| Bidirectional list traversal | ListIterator |
| Add or replace during list traversal | ListIterator |
| Index required | Traditional for |
| Concise processing action | forEach() |
| Legacy Vector or Hashtable code | Enumeration |
Check your understanding: Which mechanism safely removes matching elements from most collections during traversal?
Iterator.