Java .iterator()
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: TheArrayListto 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 stringsArrayList<String> list = new ArrayList<>();// Add items to the ArrayListlist.add("Apple");list.add("Banana");list.add("Cherry");// Get an iterator for the listIterator<String> iterator = list.iterator();// Use the iterator to traverse the listwhile (iterator.hasNext()) {String element = iterator.next();System.out.println(element);}}}
The above example will print the following in the console:
AppleBananaCherry
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours