π 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 availability
- next()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 Listtypes | 
π‘ 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 :
