Explain how collections can be accessed using an iterator with an example.

Explain how collections can be accessed using an iterator with an example.


Accessing Collections Using an Iterator in Java

In Java, an Iterator is an object that allows you to traverse (loop through) elements of a collection one at a time. It is part of the java.util package and works with any class that implements the Collection interface (such as List, Set, etc.).


Steps to Access Collection using Iterator:

  1. Get an iterator using collection.iterator()
  2. Use a while loop with hasNext() to check if more elements exist.
  3. Use next() to get the next element.

Example Using ArrayList and Iterator:

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

public class IteratorExample {
    public static void main(String[] args) {
        ArrayList<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");

        // Get Iterator
        Iterator<String> itr = fruits.iterator();

        // Access elements using Iterator
        System.out.println("Fruits list:");
        while (itr.hasNext()) {
            String fruit = itr.next();
            System.out.println(fruit);
        }
    }
}

Output:

Fruits list:
Apple  
Banana  
Mango

Iterator Methods:

MethodDescription
hasNext()Returns true if more elements exist.
next()Returns the next element in the list.
remove()Removes the current element (optional).

Advantages:

  • Works on all collection types like List, Set, etc.
  • Provides a uniform way to access elements.
  • Avoids IndexOutOfBoundsException which may occur in index-based loops.

Leave a Reply

Your email address will not be published. Required fields are marked *