Java Language – 32 – Iterators

Collections and Data Structures – Iterators
Introduction

Iterators are a fundamental part of Java collections and data structures. They provide a way to traverse and access elements within a collection in a systematic manner. In this guide, we’ll explore the concept of iterators, understand their importance, and learn how to use them effectively in Java.

What Are Iterators?

An iterator in Java is an object that allows you to traverse through the elements of a collection (like lists, sets, and maps) one at a time. It provides methods for accessing elements and advancing to the next element. Iterators are a part of the Java Collections Framework and provide a uniform way to access elements, regardless of the underlying collection type.

Using Iterators

To use an iterator, you typically follow these steps:

  1. Create an iterator object by calling the ‘iterator()’ method on a collection.
  2. Use methods like ‘hasNext()’ to check if there are more elements and ‘next()’ to retrieve the next element.
  3. Iterate through the collection until ‘hasNext()’ returns ‘false’ or as needed.

Let’s look at an example of using an iterator to traverse a list:


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

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

        // Create an iterator
        Iterator<String> iterator = fruits.iterator();

        // Traverse the list
        while (iterator.hasNext()) {
            String fruit = iterator.next();
            System.out.println(fruit);
        }
    }
}

In this example, we create an ‘ArrayList’ of fruits and then create an iterator to traverse the list. We use ‘hasNext()’ to check for the presence of more elements and ‘next()’ to retrieve and print each fruit.

Types of Iterators

Java provides different types of iterators to work with various collections. The primary iterator types are:

  • Iterator: This is a general-purpose iterator that can be used with most collections, including lists, sets, and queues.
  • ListIterator: Specifically designed for lists, it provides bidirectional traversal (both forward and backward).
  • Iterator for Maps: Maps have their own iterator interfaces, such as ‘Iterator>’ for traversing key-value pairs in a map.
Iterator in Enhanced for Loop

Java provides an enhanced for loop (for-each loop) that simplifies iterating through collections using iterators. Here’s how you can use it:


for (String fruit : fruits) {
    System.out.println(fruit);
}

This code achieves the same result as the iterator-based traversal, making your code more concise and readable.

Removing Elements

Iterators also allow you to remove elements from a collection safely. You can use the ‘remove()’ method to remove the last element returned by ‘next()’. Here’s an example:


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

In this example, we remove the element “Banana” from the list using the iterator’s ‘remove()’ method.

Conclusion

Iterators are a crucial component of Java collections, providing a systematic way to traverse and manipulate elements within collections. By understanding how to use iterators effectively, you can work with collections in a more versatile and controlled manner.