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:

  1. Is there a next element?
  2. proceed to the next item
  3. delete

The general steps for using an iterator are as follows:

  1. Create a collection object, such as a List or Set.
  2. create an iterator
  3. Is there a next element?
  4. proceed to the next step
  5. Perform operations on the acquired elements.
  6. 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.

bannerAds