Java ArrayList iterator()

The syntax of the iterator() method is:

arraylist.iterator()

iterator() Parameters

The iterator() method does not take any parameters.


iterator() Return Values

  • returns an iterator to loop through the arraylist elements

Note: The iterator returned by the method is stored in the variable of interface Iterator type.


Example 1: Java ArrayList iterator()

Output

ArrayList: Java, Python, JavaScript, Swift,

In the above example, we have created an arraylist named languages. Notice the line,

Iterator<String> iterate = languages.iterator();

Here, we have created a variable named iterate of the Iterator interface. The variable stores the iterator returned by the iterator() method.

Using iterate, we can access the elements of the arraylist.

  • hasNext: returns true if there is a next element in the arraylist
  • next(): returns the next element in the arraylist

Note: We have used the ArrayList add() method to insert elements to the arraylist.


Example 2: Get Index of Each Element of ArrayList Using iterator()

Output

Element: Index
Java: 0
Python: 1
JavaScript: 2
Swift: 3

Note: We have used the Java ArrayList indexOf() method to access the index number of the element.

The ArrayList also provides a listIterator() method to iterate through list only. To learn more, visit Java ListIterator.