Iterator in Java with Example

In this article, we will discuss how to use the Iterator interface in Java to iterate over collections such as ArrayList, LinkedList, and HashSet. We will cover the basics of using an Iterator, provide examples to demonstrate its usage, and show how to safely remove elements during iteration.

Table of Contents

  1. Introduction
  2. Using an Iterator with an ArrayList
  3. Using an Iterator with a LinkedList
  4. Using an Iterator with a HashSet
  5. Removing Elements During Iteration
  6. Complete Example
  7. Conclusion

Introduction

The Iterator interface in Java provides methods to iterate over a collection. It is part of the java.util package and is used to traverse elements one by one. The main methods provided by the Iterator interface are:

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

Using an Iterator with an ArrayList

Let's start by using an Iterator with an ArrayList.

Example

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

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

        Iterator<String> iterator = fruits.iterator();
        while (iterator.hasNext()) {
            String fruit = iterator.next();
            System.out.println(fruit);
        }
    }
}

Output:

Apple
Banana
Cherry

Using an Iterator with a LinkedList

Next, let's use an Iterator with a LinkedList.

Example

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class LinkedListIteratorExample {
    public static void main(String[] args) {
        List<String> fruits = new LinkedList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        Iterator<String> iterator = fruits.iterator();
        while (iterator.hasNext()) {
            String fruit = iterator.next();
            System.out.println(fruit);
        }
    }
}

Output:

Apple
Banana
Cherry

Using an Iterator with a HashSet

Now, let's use an Iterator with a HashSet.

Example

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class HashSetIteratorExample {
    public static void main(String[] args) {
        Set<String> fruits = new HashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        Iterator<String> iterator = fruits.iterator();
        while (iterator.hasNext()) {
            String fruit = iterator.next();
            System.out.println(fruit);
        }
    }
}

Output:

Apple
Banana
Cherry

Removing Elements During Iteration

The Iterator interface also provides a remove method, which allows us to remove elements from the collection during iteration.

Example

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

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

        Iterator<String> iterator = fruits.iterator();
        while (iterator.hasNext()) {
            String fruit = iterator.next();
            if ("Banana".equals(fruit)) {
                iterator.remove();
            }
        }

        System.out.println("Fruits after removal: " + fruits);
    }
}

Output:

Fruits after removal: [Apple, Cherry]

Complete Example

Here's a complete example that demonstrates the use of Iterator with different collections and removing elements during iteration.

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class IteratorExample {
    public static void main(String[] args) {
        // ArrayList example
        List<String> arrayList = new ArrayList<>();
        arrayList.add("Apple");
        arrayList.add("Banana");
        arrayList.add("Cherry");
        System.out.println("ArrayList elements:");
        printElements(arrayList);

        // LinkedList example
        List<String> linkedList = new LinkedList<>();
        linkedList.add("Apple");
        linkedList.add("Banana");
        linkedList.add("Cherry");
        System.out.println("LinkedList elements:");
        printElements(linkedList);

        // HashSet example
        Set<String> hashSet = new HashSet<>();
        hashSet.add("Apple");
        hashSet.add("Banana");
        hashSet.add("Cherry");
        System.out.println("HashSet elements:");
        printElements(hashSet);

        // Removing elements during iteration
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        fruits.add("Banana");
        System.out.println("Original list: " + fruits);
        removeElements(fruits, "Banana");
        System.out.println("List after removal: " + fruits);
    }

    private static void printElements(Iterable<String> collection) {
        Iterator<String> iterator = collection.iterator();
        while (iterator.hasNext()) {
            String element = iterator.next();
            System.out.println(element);
        }
    }

    private static void removeElements(List<String> list, String elementToRemove) {
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String element = iterator.next();
            if (element.equals(elementToRemove)) {
                iterator.remove();
            }
        }
    }
}

Output:

ArrayList elements:
Apple
Banana
Cherry
LinkedList elements:
Apple
Banana
Cherry
HashSet elements:
Apple
Banana
Cherry
Original list: [Apple, Banana, Cherry, Banana]
List after removal: [Apple, Cherry]

Conclusion

Using the Iterator interface in Java allows you to traverse and manipulate collections such as ArrayList, LinkedList, and HashSet. This guide provided examples of how to use an Iterator to iterate over these collections and how to safely remove elements during iteration. By understanding these concepts, you can efficiently manage elements in your collections.

Comments