You can iterate an ArrayList by using either forEach(Consumer), since Java 8, or for-each and other index-loops (while, do-while, for-index)
Apart from that, iterator and listIterator can also be used to iterate over an ArrayList
Lets walk through this tutorial to explore them in more details
Iterate forward with the Java 8+ forEach(Consumer) and for-each loop
Use Java 8+ forEach(Consumer) to iterate over an ArrayList in forwarding order (same as insertion order)
NullPointerException will be thrown if the specified consumer action or the caller list is null
@Test
public void forEachConsumer() {
List<Integer> lst = new ArrayList<>(List.of(1, 2, 3));
lst.forEach(e -> System.out.printf("%d ", e));
}
- for-each loop can also be used to iterate an ArrayList in forwarding order
@Test
public void forEach() {
List<Integer> lst = new ArrayList<>(List.of(1, 2, 3));
for(int ele : lst){
System.out.printf("%d ", ele);
}
}
forEach(Consumer) and for-each loop can only iterate in forwarding order
To iterate in reverse order, you can use either index-loops or listIterator or sort the list in reverse order first
Iterate forward and backward with index-loops
Use for-index, while-index and do-while-index loops to iterate over an ArrayList in both ways, forward and backward order
The following give you an example on iterate forward with for-index loop
@Test
public void forIndexForward() {
List<Integer> lst = new ArrayList<>(List.of(1, 2, 3));
for(int i=0; i<lst.size(); i++){
int ele = lst.get(i);
System.out.printf("%d ", ele);
}
}
- Iterate in backward order example with for-index loop
@Test
public void forIndexBackward() {
List<Integer> lst = new ArrayList<>(List.of(1, 2, 3));
for(int i=lst.size()-1; i>=0; i--){
int ele = lst.get(i);
System.out.printf("%d ", ele);
}
}
Iterate forward and backward with iterator and listIterator
- Iterate forward with iterator() example
@Test
public void iterator() {
List<Integer> lst = new ArrayList<>(List.of(1, 2, 3));
Iterator<Integer> iterator = lst.iterator();
while (iterator.hasNext()){
System.out.printf("%d ", iterator.next());
}
}
- Iterate backward with listIterator() example
@Test
public void listIterator() {
List<Integer> lst = new ArrayList<>(List.of(1, 2, 3));
ListIterator<Integer> iterator = lst.listIterator(lst.size());
while (iterator.hasPrevious()){
System.out.printf("%d ", iterator.previous());
}
}
Conclusion
In this tutorial, we learned some ways to iterate over an ArrayList in forward and backward order by using the Java 8+ forEach(Consumer), for-each and for-index loops, iterator and listIterator. You can find below the full source code