How is the usage of iterator in Java?
In Java, Iterator is an interface used to iterate through elements in a collection. It provides a uniform way to access elements in the collection without needing to understand the internal structure of the collection.
The steps for using an Iterator are as follows:
- Call the iterator() method on the collection to retrieve an Iterator object.
- Use the hasNext() method to check if there is another element.
- Retrieve the next element using the next() method.
- Remove elements from the collection using the remove() method (optional operation).
Here is a simple example demonstrating how to use an Iterator to iterate over a List collection.
List<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);
}
In the example above, we first obtain an Iterator object by calling the iterator() method of ArrayList. We then use a while loop and the hasNext() method to iterate through the elements in the collection, and finally use the next() method to retrieve and print each element.