Iterator
- Java course
- Intermediate
- Lesson 94/116
- 5 min
Learn to iterate collections with Iterator.
The Iterator<E> interface
Iterator<E> is the universal interface for walking a collection one element at a time. hasNext() asks if there is a next element; next() returns the next element and advances the cursor.
You obtain an Iterator from a List with Iterator<String> it = names.iterator();. The loop pattern is while (it.hasNext()) { String s = it.next(); }. An Iterator does not modify the collection by itself; it only reads. Removal uses a separate remove method.
The traversal pattern
The standard Iterator pattern is: get the iterator with iterator(), open a while (it.hasNext()) loop, read elements with it.next() inside. This pattern is what for-each does behind the scenes; Java implements for-each with an Iterator.
If next() is called without hasNext() and the cursor is at the end, NoSuchElementException is thrown. Always call hasNext before next in a loop.
Practice Walk the list with an Iterator
Declare List<String> names = new ArrayList<>();; add "Ayşe" and "Alex". Obtain an Iterator with Iterator<String> it = names.iterator();. Inside a while (it.hasNext()) loop, print each element with System.out.println(it.next());.
Starter code
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
// Declare List<String>, add two names, walk with Iterator and print
}
}Sample solution
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Ayşe");
names.add("Alex");
Iterator<String> it = names.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}Expected output
Ayşe Alex
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does it.hasNext() return true?
- When the cursor reached the end
- When the collection is empty
- When remove is called
- When a next element exists Correct answer
Explanation: hasNext returns true when a next element exists.
2 Complete the loop condition
while (it.____()) {
String s = it.next();
}
while (it.hasNext()) {
String s = it.next();
}
Explanation: hasNext asks if a next element exists.
3 Match the Iterator methods
| Term | Meaning |
|---|---|
hasNext() |
Has next? |
next() |
Returns the next element |
iterator() |
Gets an Iterator |
remove() |
Deletes last read |