EN
Java - how to use Iterator with ArrayList
0 points
In this article, we would like to show you how to use iterator with ArrayList in Java.
Quick solution:
xxxxxxxxxx
1
Iterator<String> myIterator = myArrayList.iterator();
2
3
while (myIterator.hasNext()) {
4
System.out.print(myIterator.next() + " ");
5
}
Iterator
is an object that can be used to loop through collections. In this article, we will focus on the ArrayList collection and loop through it.
To use Iterator, the first thing we need to do is obtain it from a Collection. To do so, we use iterator()
method in the following way:
xxxxxxxxxx
1
List<String> myArrayList = ...
2
Iterator<String> myIterator = myArrayList.iterator();
3
hasNext()
- checks if there is at least one element left to iterate over, it's commonly used as a condition in while loops.next()
- steps over the next element and obtains it.
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