.iterator()

Anonymous contributor's avatar
Anonymous contributor
Published Aug 13, 2024
Contribute to Docs

The .iterator() method is used to iterate over the elements of a collection (such as an ArrayList) one by one.

Syntax

arrayListInstance.iterator();
  • arrayListInstance: The ArrayList to be iterated.

The method returns an Iterator object, which must be of the same data type as arrayListInstance.

Example

The following example creates an ArrayList, inserts some elements using the .add() method and then iterates over it using a loop:

import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
// Create an ArrayList of strings
ArrayList<String> list = new ArrayList<>();
// Add items to the ArrayList
list.add("Apple");
list.add("Banana");
list.add("Cherry");
// Get an iterator for the list
Iterator<String> iterator = list.iterator();
// Use the iterator to traverse the list
while (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);
}
}
}

The above example will print the following in the console:

Apple
Banana
Cherry

All contributors

Contribute to Docs

Learn Java on Codecademy