Iterator in java with example

Iterator in java with example

AnAn iterator in Java is an object that allows you to traverse through a collection, one element at a time. It is a way to access elements of a collection sequentially without exposing the underlying structure of the collection.

The Iterator interface provides methods to:

  • hasNext(): Returns true if the iteration has more elements.
  • next(): Returns the next element in the iteration.
  • remove(): Removes from the underlying collection the last element returned by this iterator (optional operation).

  • Using an iterator is advantageous when you need to:
  • Traverse collections such as ArrayList, HashSet, LinkedList, etc.
  • Remove elements from a collection while iterating.

Iterator in java

Example

Here’s an example demonstrating how to use an iterator with an ArrayList:

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

public class IteratorExample {
    public static void main(String[] args) {
        // Create an ArrayList and add some elements
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Cherry");
        list.add("Date");
        // Get an iterator for the list
        Iterator<String> iterator = list.iterator();

        // Use the iterator to traverse the list
        System.out.println("Elements in the list:");
        while (iterator.hasNext()) {
            String element = iterator.next();
            System.out.println(element);
        }

        // Removing elements during iteration
        iterator = list.iterator(); // Reinitialize the iterator
        while (iterator.hasNext()) {
            String element = iterator.next();
            if (element.startsWith("B")) {
                iterator.remove(); // Remove elements that start with 'B'
            }
        }

        // Display the list after removal
        System.out.println("\nElements in the list after removal:");
        for (String element : list) {
            System.out.println(element);
        }
    }
}

Explanation

  • Creating and Populating the ArrayList:
  • An ArrayList is created and populated with some fruit names.
  • Using the Iterator:
  • An iterator is obtained for the ArrayList using the iterator() method.
  • The while loop uses hasNext() to check if there are more elements and next() to retrieve each element.
  • Removing Elements During Iteration:
  • The iterator is reinitialized to traverse the list again.
  • During iteration, elements starting with ‘B’ are removed using the remove() method.
  • Displaying the List After Removal:
  • The updated list is displayed using a for-each loop to show the effect of the removal.

Summary

An iterator in Java is a powerful tool for traversing collections. It provides methods like hasNext(), next(), and remove() to navigate and modify collections safely. The provided Java example illustrates how to use an iterator with an ArrayList.

Homepage

Readmore