-
Hajipur, Bihar, 844101
The Java Iterator is an interface that allows developers to traverse elements of a collection one by one. It belongs to the java.util package and plays a key role in accessing and modifying data stored in lists, sets, and maps safely. Unlike a basic for loop, an Iterator lets you remove or update elements during iteration without causing runtime errors like ConcurrentModificationException.
In simple terms, an Iterator acts like a cursor that moves through a collection, reading each element step by step.
An Iterator is an interface used to loop through elements in a collection such as ArrayList, LinkedList, or HashSet. When you call the iterator() method on a collection, it returns an Iterator object. This object provides three main methods: hasNext(), next(), and remove().
Example:
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
Iterator<String> it = list.iterator();
Here, the it object is an Iterator that points to the first element of the list. As it moves, it accesses each element one after another.
The working process of an Iterator is quite straightforward:
The cursor starts before the first element of the collection.
The hasNext() method checks if there’s another element available.
The next() method returns the next element and advances the cursor.
The remove() method deletes the last element returned by next().
Example:
import java.util.*;
public class IteratorExample {
public static void main(String[] args) {
ArrayList<String> colors = new ArrayList<>();
colors.add("Red");
colors.add("Blue");
colors.add("Green");
Iterator<String> it = colors.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
Output:
Red
Blue
Green
In this example, the Iterator starts at the beginning of the list and moves forward until there are no elements left.
The Iterator interface provides three key methods:
Checks if there are more elements in the collection. Returns true if at least one element is left, otherwise false.
Returns the next element in the sequence. Every call to next() moves the pointer to the following element.
Removes the last element returned by next(). This helps safely delete elements while looping.
Example:
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Mango");
fruits.add("Orange");
fruits.add("Grapes");
Iterator<String> iterator = fruits.iterator();
while (iterator.hasNext()) {
String fruit = iterator.next();
if (fruit.equals("Orange")) {
iterator.remove();
}
}
System.out.println(fruits);
Output:
[Mango, Grapes]
This example shows how remove() prevents errors when modifying a collection during iteration.
While for loops and enhanced for loops can also be used to access elements in a collection, they come with limitations. For example, you cannot safely remove or modify elements while iterating using a for-each loop. Doing so can lead to a ConcurrentModificationException.
The Iterator provides a safer approach because it allows element removal during iteration and works consistently across all collection types.
Use a for-each loop when you just want to read data, and use an Iterator when you need to modify data during traversal.
import java.util.*;
public class HashSetIteratorExample {
public static void main(String[] args) {
HashSet<String> names = new HashSet<>();
names.add("Aarushi");
names.add("Riya");
names.add("Tanya");
Iterator<String> it = names.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
Output:
Aarushi
Riya
Tanya
The HashMap class does not directly return an Iterator, but you can use its entrySet() method to iterate over key-value pairs.
import java.util.*;
public class HashMapIteratorExample {
public static void main(String[] args) {
HashMap<Integer, String> students = new HashMap<>();
students.put(1, "Anjali");
students.put(2, "Neha");
students.put(3, "Pooja");
Iterator<Map.Entry<Integer, String>> it = students.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> entry = it.next();
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
Output:
1: Anjali
2: Neha
3: Pooja
| Feature | Iterator | ListIterator |
|---|---|---|
| Supported Collections | All | Only List types |
| Traversal | Forward only | Both directions |
| Add Element | No | Yes |
| Remove Element | Yes | Yes |
| Get Index | No | Yes |
The ListIterator interface extends Iterator and adds more flexibility, such as moving backward and adding elements while iterating.
Works with all types of collections (List, Set, Queue)
Prevents runtime errors during modification
Simplifies element removal
Makes traversal consistent across different data structures
Reduces the chance of logical errors in iteration logic
Calling next() without checking hasNext(): This can throw a NoSuchElementException.
Using remove() before calling next(): The remove() method should always follow a next() call.
Modifying a collection directly while iterating: Always use iterator.remove() to avoid ConcurrentModificationException.
import java.util.*;
public class ExpiredItems {
public static void main(String[] args) {
ArrayList<String> items = new ArrayList<>();
items.add("Milk");
items.add("Bread");
items.add("Eggs");
Iterator<String> it = items.iterator();
while (it.hasNext()) {
String item = it.next();
if (item.equals("Bread")) {
it.remove(); // remove expired item
}
}
System.out.println("Available items: " + items);
}
}
Output:
Available items: [Milk, Eggs]
This is a realistic scenario where an Iterator helps manage data safely.
The Java Iterator is an essential interface for traversing collections in a safe and flexible manner. It provides uniform methods to read and modify elements without breaking the collection structure. By using hasNext(), next(), and remove(), you can easily loop through data and perform updates during iteration. Understanding Iterators also helps in working with advanced Java data structures like Lists, Sets, and Maps more efficiently.
Write a Java program to create an ArrayList of names and use an Iterator to print each name.
Create a program that uses an Iterator to remove all even numbers from an ArrayList of integers.
Write a program to iterate through a HashSet of colors using an Iterator and display all elements.
Create a Java program to iterate through a LinkedList of student names and count how many names start with the letter ‘A’.
Write a program that uses an Iterator to find and remove all duplicate elements from an ArrayList.
Create a program to iterate through a HashMap and print both keys and values using an Iterator.
Write a Java program that uses an Iterator to display only those elements from a List that are longer than 5 characters.
Create a program that uses iterator.remove() to delete specific words from a List of strings.
Write a Java program that demonstrates how to safely iterate through a Set while removing elements that meet a given condition.
Create a program using an Iterator that prints the sum of all numbers in an ArrayList of integers.