Java Iterator โ Complete Guide for Traversing Lists, Sets & Maps
Introduction โ Why Java Iterator Is Useful
When working with Java Collections like ArrayList, HashSet, or HashMap, you often need a standard way to traverse through elements โ regardless of the collection type. Thatโs where the Java Iterator interface becomes indispensable.
A Java Iterator allows sequential access to elements in a forward-only direction, making it ideal for generic, type-safe iteration.
By the end of this article, you’ll learn:
What an Iterator is and how it works
How to iterate over lists, sets, and maps
How to safely remove elements during iteration
How Iterator compares with for-each and ListIterator
What Is an Iterator in Java?
Iteratoris an interface injava.utilthat provides methods to traverse and manipulate collections in a uniform way.
It supports:
- Forward traversal
- Safe removal during iteration
Iterator Methods
| Method | Description |
|---|---|
hasNext() | Checks if another element exists |
next() | Returns the next element |
remove() | Removes the last element returned by next() (optional) |
Basic Syntax โ Using Iterator with ArrayList
import java.util.*;
public class IteratorDemo {
public static void main(String[] args) {
List<String> colors = new ArrayList<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
Iterator<String> it = colors.iterator();
while (it.hasNext()) {
String color = it.next();
System.out.println(color);
}
}
}
Explanation:
iterator()returns anIteratorfor the listhasNext()checks if another element is presentnext()fetches the next element
Removing Elements with Iterator (Safely)
List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Iterator<Integer> it = numbers.iterator();
while (it.hasNext()) {
Integer num = it.next();
if (num % 2 == 0) {
it.remove(); // Safe removal
}
}
System.out.println(numbers); // [1, 3, 5]
Do not use list.remove() directly inside a loop โ it throws ConcurrentModificationException.
Using Iterator with Other Collections
Set Example
Set<String> set = new HashSet<>(Set.of("A", "B", "C"));
Iterator<String> it = set.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
Works exactly like with lists
Iterating Over Map with Iterator
Map<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> entry = it.next();
System.out.println(entry.getKey() + " = " + entry.getValue());
}
entrySet() gives a Set of key-value pairs that can be iterated
Iterator vs For-each Loop
| Feature | Iterator | for-each loop |
|---|---|---|
| Direction | Forward only | Forward only |
| Can remove elements? | Yes (iterator.remove()) | No |
| Generic Collection Type | Yes | Yes |
| Safe in concurrent mods | Safer | May cause ConcurrentModificationException |
| Complexity | Slightly more verbose | Simpler syntax |
Advanced: ListIterator (Bi-directional)
ListIterator<String> listIt = colors.listIterator();
while (listIt.hasNext()) {
System.out.println("Forward: " + listIt.next());
}
while (listIt.hasPrevious()) {
System.out.println("Backward: " + listIt.previous());
}
ListIterator supports:
- Backward traversal (
hasPrevious(),previous()) - Add, replace, or remove during iteration
Only works with List collections
Best Practices for Java Iterator
Use iterator.remove() instead of collection.remove() during iteration
Prefer for-each for read-only traversal
Use ListIterator only when bidirectional traversal is required
Avoid modifying collection structure outside the iterator loop
Use Java 8 forEachRemaining() to consume the rest of the iteration
Summary
Iteratoris a universal tool for traversing collections in Java- Provides safe, forward-only access with optional removal
- Works across List, Set, and Map structures
- Choose
ListIteratorfor bi-directional iteration on lists - Always use
iterator.remove()for modifying elements during iteration
FAQs โ Java Iterator
What is the difference between Iterator and ListIterator?
Iterator: works for all collections, forward onlyListIterator: works only forList, supports bidirectional traversal and add/replace
Can I use Iterator on a Map?
Yes. Use map.entrySet().iterator() to iterate through key-value pairs.
What happens if I remove an element directly inside a loop?
Youโll get a ConcurrentModificationException unless you use the iteratorโs remove() method.
Is Iterator thread-safe?
No. Use ConcurrentHashMap, CopyOnWriteArrayList, or external synchronization for thread safety.
Can Iterator be reused?
No. Once fully traversed, you must call collection.iterator() again to restart iteration.
Share Now :
