In this example we will show how to iterate through an ArrayList object in reverse direction with Java ListIterator’s previous and hasPrevious methods .
Source Code
package com.beginner.examples;
import java.util.ArrayList;
import java.util.ListIterator;
public class TraverseReverseUsingListIterator {
public static void main(String[] args) {
//create ArrayList.
ArrayList arrayList = new ArrayList();
arrayList.add("A");
arrayList.add("B");
arrayList.add("C");
arrayList.add("D");
//Get ListIterator using listIterator() method.
ListIterator listIterator = arrayList.listIterator();
System.out.println("Using ListIterator to traversing ArrayList in forward direction");
while(listIterator.hasNext()) {
System.out.println(listIterator.next());
}
System.out.println("Using ListIterator to traversing ArrayList in reverse direction");
while(listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
}
}
Output:
Using ListIterator to traversing ArrayList in forward direction
A
B
C
D
Using ListIterator to traversing ArrayList in reverse direction
D
C
B
A
References
Imported packages in Java documentation: