Java Iterators
A Java Iterator is an object that moves through a collection one item at a time. It gives you a standard way to read values from lists, sets, and other collections without using an index.
Iterators are useful when you want the same loop style for different collection types, or when you need to remove items safely during a loop.
Create An Iterator
Most collection classes have an iterator() method. Import java.util.Iterator, call iterator() on the collection, then use hasNext() and next() to move through the items.
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
ArrayList<String> languages = new ArrayList<>();
languages.add("Java");
languages.add("Python");
languages.add("C++");
Iterator<String> iterator = languages.iterator();
while (iterator.hasNext()) {
String language = iterator.next();
System.out.println(language);
}
}
}
Output:
Java
Python
C++
The hasNext() method returns true if another item is available. The next() method returns that item and moves the iterator forward. Call next() only after checking hasNext(), otherwise the program can throw an exception when there are no more items.
Why Use An Iterator?
A for-each loop is often the simplest way to read a collection, but it does not expose the iterator object directly. An explicit Iterator is helpful when you need more control over the loop.
- Use a for-each loop for simple reading.
- Use an
Iteratorwhen you need to remove items while looping. - Use an
Iteratorwhen you want code that works with collections that do not support indexes.
Remove Items Safely
Do not remove items directly from a collection inside a for-each loop. Instead, call the iterator’s remove() method after next() returns the item you want to delete.
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
ArrayList<String> topics = new ArrayList<>();
topics.add("Java");
topics.add("Python");
topics.add("SQL");
topics.add("Kotlin");
Iterator<String> iterator = topics.iterator();
while (iterator.hasNext()) {
String topic = iterator.next();
if (topic.length() <= 4) {
iterator.remove();
}
}
System.out.println(topics);
}
}
Output:
[Python, Kotlin]
This loop removes Java and SQL because their lengths are less than or equal to 4. The call to iterator.remove() removes the last item returned by next().
Iterate Over Map Entries
A Map stores key-value pairs, so you usually iterate over its entrySet(). Each entry gives access to both the key and the value.
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
LinkedHashMap<String, Integer> scores = new LinkedHashMap<>();
scores.put("Alice", 90);
scores.put("Ben", 85);
scores.put("Cara", 92);
Iterator<Map.Entry<String, Integer>> iterator = scores.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
Output:
Alice: 90
Ben: 85
Cara: 92
This example uses LinkedHashMap so the output follows insertion order. With a regular HashMap, you should not depend on a specific iteration order.
Common Iterator Methods
hasNext()checks whether another item is available.next()returns the next item and advances the iterator.remove()removes the last item returned bynext().
Common Mistakes
- Calling
next()without first checkinghasNext(). - Calling
remove()before callingnext(). - Modifying the collection directly while an iterator loop is running.
- Expecting every collection type to have indexes like a list.
Takeaway: an Iterator is a safe, standard way to move through collection items one at a time, especially when a loop may remove values.
