EN
Java - iterate through Arraylist using iterator
0 points
In this article, we would like to show you how to iterate through ArrayList using iterator in Java.
Quick solution:
xxxxxxxxxx
1
Iterator<String> myIterator = myArrayList.iterator();
2
3
while (myIterator.hasNext()) {
4
System.out.print(myIterator.next() + " ");
5
}
In this example, we create an iterator for letters
ArrayList to display all the elements in the proper order.
xxxxxxxxxx
1
import java.util.*;
2
3
public class Example {
4
5
public static void main(String[] args) {
6
List<String> letters = new ArrayList<>();
7
8
letters.add("A");
9
letters.add("B");
10
letters.add("C");
11
12
// create an iterator
13
Iterator<String> myIterator = letters.iterator();
14
15
// display values after iterating through the ArrayList
16
System.out.println("The iterator values of the list are: ");
17
while (myIterator.hasNext()) {
18
System.out.print(myIterator.next() + " ");
19
}
20
}
21
}
Output:
xxxxxxxxxx
1
The iterator values of the list are:
2
A B C