Iterate over ArrayList using Iterator in Java

In Java, the Iterator interface provides a way to traverse a collection of elements, such as an ArrayList, in a sequential manner. 

Using an Iterator is often preferred when you need to remove elements from the collection while iterating over it. 

This guide will cover how to use an Iterator to iterate over an ArrayList, explain how it works, and provide examples to demonstrate its functionality. Additionally, we will cover a real-world use case to illustrate its application.

Table of Contents

  1. Introduction
  2. Using an Iterator to Iterate Over an ArrayList
  3. How It Works
  4. Examples
    • Basic Iteration
    • Removing Elements While Iterating
  5. Real-World Use Case
  6. Conclusion

Introduction

The Iterator interface provides methods to traverse elements in a collection. It offers more flexibility compared to traditional for-loops, especially when you need to modify the collection during iteration. The Iterator interface includes three main methods:

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

Using an Iterator to Iterate Over an ArrayList

To use an Iterator to iterate over an ArrayList, follow these steps:

  1. Obtain an Iterator from the ArrayList using the iterator() method.
  2. Use a loop to iterate through the elements, checking for more elements with hasNext() and retrieving the next element with next().

How It Works

The Iterator interface works by maintaining a cursor that points to the current position in the collection. As you call next(), the cursor advances, allowing you to access each element in sequence. The remove() method removes the last element returned by next(), which is useful for conditional removals during iteration.

Examples

Basic Iteration

The following example demonstrates how to use an Iterator to iterate over an ArrayList.

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

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

        // Obtain an iterator
        Iterator<String> iterator = list.iterator();

        // Iterate through the ArrayList
        while (iterator.hasNext()) {
            String element = iterator.next();
            System.out.println(element);
        }
    }
}

Output:

Apple
Banana
Orange

Removing Elements While Iterating

The following example demonstrates how to use an Iterator to remove elements from an ArrayList while iterating over it.

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

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

        System.out.println("Original list: " + list);

        // Obtain an iterator
        Iterator<String> iterator = list.iterator();

        // Remove elements while iterating
        while (iterator.hasNext()) {
            String element = iterator.next();
            if (element.equals("Banana")) {
                iterator.remove();
            }
        }

        System.out.println("List after removing 'Banana': " + list);
    }
}

Output:

Original list: [Apple, Banana, Orange, Banana]
List after removing 'Banana': [Apple, Orange]

Real-World Use Case

Filtering User Sessions

In a web application, you might store user sessions in an ArrayList. If you need to remove inactive sessions, you can use an Iterator to iterate through the list and remove sessions based on a condition.

Example

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

class UserSession {
    String username;
    boolean isActive;

    UserSession(String username, boolean isActive) {
        this.username = username;
        this.isActive = isActive;
    }

    @Override
    public String toString() {
        return username + " (Active: " + isActive + ")";
    }
}

public class UserSessionManagement {
    public static void main(String[] args) {
        List<UserSession> sessions = new ArrayList<>();
        sessions.add(new UserSession("alice", true));
        sessions.add(new UserSession("bob", false));
        sessions.add(new UserSession("charlie", true));
        sessions.add(new UserSession("dave", false));

        System.out.println("Original sessions: " + sessions);

        // Obtain an iterator
        Iterator<UserSession> iterator = sessions.iterator();

        // Remove inactive sessions
        while (iterator.hasNext()) {
            UserSession session = iterator.next();
            if (!session.isActive) {
                iterator.remove();
            }
        }

        System.out.println("Active sessions: " + sessions);
    }
}

Output:

Original sessions: [alice (Active: true), bob (Active: false), charlie (Active: true), dave (Active: false)]
Active sessions: [alice (Active: true), charlie (Active: true)]

Conclusion

Using an Iterator to iterate over an ArrayList in Java provides a flexible way to traverse and modify the collection. By understanding how to use the Iterator interface, you can efficiently perform operations such as conditional removals during iteration. This method is particularly useful in real-world applications where you need to manage collections dynamically.

Comments