Introduce Java Iterator and give examples
In Java, an Iterator
is an interface that provides a way to traverse a collection (like a list, set, or map) without exposing the underlying structure of the collection. It allows you to iterate over the elements in a collection in a sequential manner, providing methods to check for the presence of more elements, retrieve the next element, and remove elements from the collection during iteration.
boolean hasNext()
: Returns true
if the iteration has more elements.E next()
: Returns the next element in the iteration.void remove()
: Removes from the underlying collection the last element returned by the iterator (optional operation).Here’s a simple example demonstrating how to use an Iterator
with a List
in Java:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IteratorExample {
public static void main(String[] args) {
// Create a list of strings
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
fruits.add("Date");
// Get an iterator for the list
Iterator<String> iterator = fruits.iterator();
// Iterate through the list using the iterator
while (iterator.hasNext()) {
String fruit = iterator.next();
System.out.println(fruit);
// Remove "Banana" from the list
if (fruit.equals("Banana")) {
iterator.remove();
}
}
// Print the modified list
System.out.println("After removal: " + fruits);
}
}
Apple
Banana
Cherry
Date
After removal: [Apple, Cherry, Date]
ArrayList
of strings representing fruits.Iterator
for the list using the iterator()
method.while
loop to check if there are more elements using hasNext()
. Inside the loop, we retrieve the next element with next()
.remove()
to remove it from the list.remove()
method can only be called once per call to next()
. If you try to call it before calling next()
, or if you call it multiple times after a single next()
, it will throw an IllegalStateException
.ConcurrentModificationException
.The Iterator
interface is a powerful tool in Java for traversing collections. It abstracts the iteration process and provides a clean way to manipulate elements during iteration.