Java Iterator Methods
In Java, an Iterator is used to traverse (loop through) elements of a collection such as ArrayList, LinkedList, HashSet, etc.
Iterator belongs to the java.util package and is part of the Collection Framework.
1. Importing Iterator
import java.util.Iterator;
import java.util.ArrayList;
2. Creating an Iterator
To use Iterator, first create a collection and then call the iterator() method.
ArrayList list = new ArrayList();
list.add("Java");
list.add("Python");
list.add("C++");
Iterator it = list.iterator();
3. hasNext()
The hasNext() method checks if there is another element in the collection.
while(it.hasNext()) {
System.out.println(it.hasNext());
}
Usually, we use hasNext() inside a loop condition.
4. next()
The next() method returns the next element in the collection.
while(it.hasNext()) {
System.out.println(it.next());
}
5. remove()
The remove() method removes the last element returned by next().
Iterator it2 = list.iterator();
while(it2.hasNext()) {
String value = it2.next();
if(value.equals("Python")) {
it2.remove();
}
}
System.out.println(list);
Complete Example
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
ArrayList names = new ArrayList();
names.add("Rahul");
names.add("Amit");
names.add("Neha");
Iterator it = names.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
}
Why Use Iterator?
- It works with all Collection classes.
- It safely removes elements while iterating.
- It avoids ConcurrentModificationException.
- It provides a standard way to traverse collections.
Iterator vs For-Each Loop
- For-each loop is simple and easy to use.
- Iterator allows removing elements safely.
- Iterator provides more control while traversing.
Important Points
- Always call next() before remove().
- Do not modify collection directly while iterating.
- Use hasNext() to avoid errors.
- Iterator works only in forward direction.
Conclusion
The Iterator interface provides methods like hasNext(), next(), and remove() to traverse collections.
It is an important concept in Java Collection Framework.
Tip: Use Iterator when you need safe removal of elements during iteration.