Java Iterator

https:/‮gi.www/‬iftidea.com

In Java, an Iterator is an interface that provides a way to access the elements in a collection object one at a time. It is a part of the java.util package and is used to traverse a collection of objects, such as a List, Set, or Map.

The Iterator interface has three methods:

  1. boolean hasNext(): Returns true if there are more elements in the collection.

  2. E next(): Returns the next element in the collection.

  3. void remove(): Removes the last element returned by the iterator from the underlying collection.

Here's an example of how to use an Iterator in Java:

import java.util.ArrayList;
import java.util.Iterator;

public class IteratorExample {
    public static void main(String[] args) {
        // Create a new ArrayList
        ArrayList<String> list = new ArrayList<>();

        // Add some elements to the list
        list.add("apple");
        list.add("banana");
        list.add("cherry");

        // Create an Iterator for the list
        Iterator<String> iterator = list.iterator();

        // Iterate over the list using the Iterator
        while (iterator.hasNext()) {
            String element = iterator.next();
            System.out.println(element);
        }
    }
}

Output:

apple
banana
cherry

In the example above, we have created an ArrayList of strings, and added three elements to it. We have then created an Iterator for the list using the iterator() method of the ArrayList class. We have used a while loop to iterate over the list using the hasNext() and next() methods of the Iterator. The hasNext() method returns true if there are more elements in the list, and the next() method returns the next element in the list. We have printed each element to the console using System.out.println().

Note that the Iterator interface can also be used to remove elements from a collection using the remove() method. This method removes the last element returned by the Iterator from the underlying collection. However, it is important to use this method carefully, as it can cause unexpected behavior if used improperly.