In Java, the Iterator
interface provides a way to traverse (or iterate over) the elements in a collection without exposing the underlying implementation of the collection. It allows you to sequentially access each element in the collection and perform operations like removal, if supported by the underlying collection.
Table of Contents
- Creating an Iterator
- Using Iterator Methods
- Example: Using Iterator to Traverse a List
- Example: Using Iterator to Traverse a Set
1. Introduction to Iterator
The Iterator
interface is part of the Java Collections Framework (java.util
package). It provides methods to iterate over the elements of a collection in a forward direction. The main advantage of using an iterator is that it provides a common way to iterate over different types of collections such as lists, sets, and maps, without knowing their specific implementation.
Key points about Iterator
:
- It is a unidirectional cursor, meaning it allows you to move forward through the elements of a collection.
- It provides methods to check if there are more elements (
hasNext()
) and retrieve the next element (next()
). - It also supports removal of elements using the
remove()
method, if the underlying collection allows it.
2. Using Iterator
2.1. Creating an Iterator
To obtain an Iterator
for a collection, you typically use the iterator()
method provided by the Collection
interface. Here’s how you create an Iterator
:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IteratorExample {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
// Get an iterator for the list
Iterator<String> iterator = names.iterator();
}
}
2.2. Using Iterator Methods
Once you have an Iterator
, you can use the following methods to iterate over the elements:
hasNext()
: Returnstrue
if there are more elements in the collection.next()
: Returns the next element in the collection and moves the cursor forward.remove()
: Removes the last element returned bynext()
from the collection (optional operation).
2.3. Example: Using Iterator to Traverse a List
Let’s see an example of using an Iterator
to traverse a List
:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IteratorExample {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
// Get an iterator for the list
Iterator<String> iterator = names.iterator();
// Traverse the list using the iterator
while (iterator.hasNext()) {
String name = iterator.next();
System.out.println(name);
}
}
}
Output:
Alice
Bob
Charlie
2.4. Example: Using Iterator to Traverse a Set
You can also use an Iterator
to traverse a Set
:
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class IteratorExample {
public static void main(String[] args) {
Set<Integer> numbers = new HashSet<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
// Get an iterator for the set
Iterator<Integer> iterator = numbers.iterator();
// Traverse the set using the iterator
while (iterator.hasNext()) {
int number = iterator.next();
System.out.println(number);
}
}
}
Output:
10
20
30
2.5 Example: Iterating over the Entry Set
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
3. Conclusion
The Iterator
interface in Java provides a simple and uniform way to iterate over elements in collections such as lists, sets, and other data structures. It allows you to access elements sequentially, check for more elements, and optionally remove elements from the underlying collection. Understanding and using iterators is essential for working with Java collections effectively.
In this tutorial, you learned how to:
- Create an
Iterator
for a collection usingiterator()
. - Use methods like
hasNext()
andnext()
to traverse the collection. - Optionally remove elements using
remove()
.