π 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 :
