Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java ArrayList iterator() method
Syntax and Examples


Introduction

The `iterator()` method in Java's ArrayList provides a way to safely traverse and modify the list elements. It returns an Iterator object that allows you to iterate over the list without directly accessing its indices, which can be crucial when you're adding or removing elements during iteration.

Syntax

  public Iterator<E> iterator()

Parameters

Parameter Description
N/A This method doesn't accept any parameters.

Return Value

The iterator() method returns an instance of the Iterator<E> interface. This iterator object is used to iterate over the elements of the ArrayList.

Examples

Example 1: Basic Iteration

This example demonstrates how to use the `iterator()` method to simply loop through an ArrayList and print each element.

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

public class IteratorExample1 {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");

        Iterator<String> iterator = names.iterator();

        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

Alice
Bob
Charlie

Explanation: First, we create an ArrayList of strings called names and add three names to it. Then, we obtain an iterator using the iterator() method. The while loop continues as long as there are more elements (checked by hasNext()). Inside the loop, next() retrieves the next element in the list and prints it.

Example 2: Removing Elements During Iteration

This example shows how to safely remove elements from an ArrayList while iterating using the iterator's remove() method. Directly modifying the ArrayList during iteration with a standard loop can lead to unexpected behavior (e.g., skipping elements or ConcurrentModificationException). The iterator provides a safe way to do this.

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

public class IteratorExample2 {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);
        numbers.add(40);
        numbers.add(50);

        Iterator<Integer> iterator = numbers.iterator();

        while (iterator.hasNext()) {
            int number = iterator.next();
            if (number % 2 == 0) { // Remove even numbers
                iterator.remove();
            }
        }

        System.out.println(numbers);
    }

[10, 20, 30, 40, 50]
[10, 30, 50]

Explanation: We create an ArrayList of integers. We obtain an iterator and iterate through the list. Inside the loop, we check if each number is even. If it is, we use the iterator's remove() method to remove that element from the list safely. The final ArrayList contains only odd numbers.

Example 3: Checking for a Specific Element

This example demonstrates how to search for a specific element within an ArrayList using the iterator. It's useful when you don't know the index of the element you are looking for.

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

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

        Iterator<String> iterator = fruits.iterator();
        boolean found = false;

        while (iterator.hasNext()) {
            if (iterator.next().equals("Banana")) {
                found = true;
                break; // Exit the loop once found
            }
        }

        if (found) {
            System.out.println("Banana found in the list.");
        } else {
            System.out.println("Banana not found in the list.");
        }
    }
Banana found in the list.

Explanation: We create an ArrayList of strings (fruits). We obtain an iterator and iterate through the list, checking if each element is equal to "Banana". If it finds “Banana”, the boolean variable `found` is set to true, then loop breaks using break;. Finally, we check the value of `found` to determine whether or not “Banana” was in the ArrayList.


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M