Java - Iterator

Java Iterator is an interface that allows traversing a collection in a forward direction. It provides a way to access the elements of a collection sequentially, without knowing the underlying implementation of the collection.

The Iterator interface has three methods:

  • boolean hasNext(): This method returns true if the iteration has more elements.
  • E next(): This method returns the next element in the iteration.
  • void remove(): This method removes the last element returned by the iterator.

To use an Iterator, you first need to obtain it from the collection using the iterator() method. Here is an example:

ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");

Iterator<String> it = list.iterator();
while (it.hasNext()) {
    String element = it.next();
    System.out.println(element);
}

In this example, we create an ArrayList and add three elements to it. Then we get an Iterator from the list and use it to iterate over the elements. We call the hasNext() method to check if there are more elements, and if so, we call the next() method to get the next element. We can then process the element in any way we want.

The Iterator interface is widely used in Java collections, such as ArrayList, LinkedList, HashSet, and HashMap. It provides a convenient and efficient way to access the elements of a collection, especially when we don't know the size or the underlying implementation of the 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");
      list.add("kiwi");
      
      Iterator<String> iterator = list.iterator();
      while (iterator.hasNext()) {
         String element = iterator.next();
         System.out.println(element);
      }
   }
}

In this example, we create an ArrayList of String objects and add some elements to it. We then create an iterator for the list using the iterator() method of the ArrayList class. We use a while loop to iterate over the list using the hasNext() and next() methods of the iterator. For each element in the list, we print it to the console. This code will output:

This example demonstrates how to use an iterator to iterate over the elements of an ArrayList. By using an iterator, we can access each element of the list in turn without needing to know the size of the list or the type of the elements.