What is the usage of Java iterators?
Java iterators are objects used to traverse elements in collection classes such as List, Set, and Map. They offer a unified way to access each element in a collection without having to expose the internal implementation of the collection.
Common methods of an iterator include:
- Is there a next element?
- proceed to the next item
- delete
The general steps for using an iterator are as follows:
- Create a collection object, such as a List or Set.
- create an iterator
- Is there a next element?
- proceed to the next step
- Perform operations on the acquired elements.
- delete
Here is a sample code demonstrating how to use iterators to traverse elements in an ArrayList collection.
import java.util.ArrayList;
import java.util.Iterator;
public class IteratorExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);
}
}
}
The output result is:
Apple
Banana
Orange
By using iterators, we can easily traverse through the elements in a collection and perform corresponding operations. The use of iterators is not limited to collection classes, but also applies to other custom classes that implement the Iterable interface.