Java Iterator Methods β Full Guide with Examples (2025)
Introduction β Why Java Iterator Methods Matter
In Java, the Iterator is a fundamental interface used to traverse collections like ArrayList, HashSet, and more. When working with collections, especially during looping, removal, or conditional filtering, Iterator methods allow:
- Safe traversal of elements
- Element removal without
ConcurrentModificationException - Compatibility with all Java Collections Framework classes
All
Collectiontypes injava.utilpackage provide aniterator()method.
What Is a Java Iterator?
An Iterator is an object that enables sequential access to elements in a collection without exposing its structure.
import java.util.Iterator;
Iterator<Type> it = collection.iterator();
Commonly used with: List, Set, Queue, etc.
Core Java Iterator Methods
| Method | Purpose |
|---|---|
hasNext() | Checks if another element exists |
next() | Returns the next element |
remove() | Removes the last element returned by next() |
Note:
remove()can only be called once pernext(), or it throwsIllegalStateException.
Java Iterator Method Examples
1. hasNext() + next() β Traverse Elements
import java.util.*;
public class IteratorExample {
public static void main(String[] args) {
List<String> languages = Arrays.asList("Java", "Python", "C++");
Iterator<String> it = languages.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
Output:
Java
Python
C++
Explanation:
hasNext()checks for availabilitynext()returns and moves to the next item
2. remove() β Safe Removal While Iterating
List<Integer> numbers = new ArrayList<>(List.of(1, 2, 3, 4, 5));
Iterator<Integer> it = numbers.iterator();
while (it.hasNext()) {
if (it.next() % 2 == 0) {
it.remove();
}
}
System.out.println(numbers); // Output: [1, 3, 5]
Explanation: Removes even numbers safely while iterating.
Don’t use list.remove(item) inside a loop β it causes ConcurrentModificationException.
3. Enhanced For-Loop vs Iterator
for (String lang : languages) {
System.out.println(lang);
}
Cleaner but read-only: Cannot safely remove items with enhanced for-loop.
Java ListIterator (Advanced)
If you need bidirectional traversal, use ListIterator:
List<String> cities = new ArrayList<>(List.of("London", "Paris", "Tokyo"));
ListIterator<String> li = cities.listIterator();
while (li.hasNext()) {
System.out.println(li.next());
}
while (li.hasPrevious()) {
System.out.println(li.previous());
}
ListIterator Methods:
| Method | Purpose |
|---|---|
hasPrevious() | Checks if a previous element exists |
previous() | Returns the previous element |
add(E) | Adds element at current cursor position |
set(E) | Replaces last element returned |
nextIndex() / previousIndex() | Get element indexes |
Summary Table β Iterator vs ListIterator
| Feature | Iterator | ListIterator |
|---|---|---|
| Traverse Forward | Yes | Yes |
| Traverse Backward | No | Yes |
| Remove Element | Yes | Yes |
| Add/Replace Element | No | Yes |
| Works with All Collections | Yes | Only List types |
Best Practices with Iterators
- Use
iterator.remove()for safe element deletion - Prefer enhanced
for-eachloop for read-only operations - Avoid calling
remove()without callingnext()first - Use
ListIteratoronly when modification or reverse traversal is needed
FAQs on Java Iterator Methods
Can I use Iterator with HashMap?
Yes. Use it on entrySet() or keySet():
Iterator<Map.Entry<String, Integer>> it = map.entrySet().iterator();
What happens if I call next() when no element exists?
It throws a NoSuchElementException.
Can I use remove() twice in a row?
No. You must call next() before each remove().
Whatβs the difference between Iterator and Enumeration?
Iterator is more modern and supports removal.Enumeration is read-only and legacy (used in old APIs like Vector).
Is Iterator thread-safe?
No. Use ConcurrentHashMap or synchronized wrappers for thread safety.
Share Now :
