
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Use ListIterator to Traverse an ArrayList in Reverse Direction in Java
A ListIterator can be used to traverse the elements in the forward direction as well as the reverse direction in the List Collection. So the ListIterator is only valid for classes such as LinkedList, ArrayList etc.
The method hasPrevious( ) in ListIterator returns true if there are more elements in the List while traversing in the reverse direction and false otherwise. The method previous( ) returns the previous element in the List and reduces the cursor position backward.
A program that demonstrates this is given as follows −
Example
import java.util.ArrayList; import java.util.ListIterator; public class Demo { public static void main(String[] args) { ArrayList<String> aList = new ArrayList<String>(); aList.add("Amanda"); aList.add("Peter"); aList.add("Julie"); aList.add("James"); aList.add("Emma"); ListIterator<String> li = aList.listIterator(); while (li.hasNext()) { li.next(); } System.out.println("The ArrayList elements in the reverse direction are: "); while (li.hasPrevious()) { System.out.println(li.previous()); } } }
Output
The ArrayList elements in the reverse direction are: Emma James Julie Peter Amanda
Now let us understand the above program.
The ArrayList is created and ArrayList.add() is used to add the elements to the ArrayList. A code snippet which demonstrates this is as follows −
ArrayList<String> aList = new ArrayList<String>(); aList.add("Amanda"); aList.add("Peter"); aList.add("Julie"); aList.add("James"); aList.add("Emma");
Then the ListIterator interface is used to display the ArrayList elements in the reverse direction. A code snippet which demonstrates this is as follows −
ListIterator<String> li = aList.listIterator(); while (li.hasNext()) { li.next(); } System.out.println("The ArrayList elements in the reverse direction are: "); while (li.hasPrevious()) { System.out.println(li.previous()); }