What is Iterator in Java? Explain with example

Iterator in Java

Iterator in Java – A Java Iterator is an interface that allows you to traverse through a collection of objects, such as lists or sets, one at a time. It provides methods to check if there are more elements in the collection, retrieve the next element, and optionally remove elements from the collection during iteration.

Key Methods of Iterator in Java

  • hasNext(): Returns true if there are more elements to iterate over.
  • next(): Returns the next element in the iteration.
  • remove(): Removes the last element returned by the iterator from the collection. This method is optional and may not be supported by all iterator implementations.

Example Usage of Iterator in Java

Here is a simple example that demonstrates how to use an Iterator to iterate over a List of strings:

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

public class IteratorExample {
    public static void main(String[] args) {
        // Creating a list of strings
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        fruits.add("Date");

        // Getting the iterator
        Iterator<String> iterator = fruits.iterator();

        // Iterating through the list
        while (iterator.hasNext()) {
            // Getting the next element
            String fruit = iterator.next();
            System.out.println(fruit);
            
            // Removing an element (optional)
            if (fruit.equals("Banana")) {
                iterator.remove();
            }
        }

        // Printing the list after iteration to see the effect of removal
        System.out.println("List after iteration: " + fruits);
    }
}

Explanation

  • List Creation: A list of strings is created and populated with fruit names.
  • Getting the Iterator: The iterator() method is called on the list to obtain an Iterator object.
  • Iterating: The while loop checks if there are more elements using hasNext(). Inside the loop, next() retrieves each element. In this example, if the element is “Banana”, it is removed using the remove() method.
  • Printing the List: After iteration, the list is printed to show the effect of the removal.

Output

Apple
Banana
Cherry
Date
List after iteration: [Apple, Cherry, Date]

This example illustrates how to use an Iterator to traverse and modify a collection. Note that attempting to use the remove() method outside the context of next() or on an unsupported collection will result in an UnsupportedOperationException.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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