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
Iterate through elements of a LinkedList using a ListIterator in Java
A ListIterator can be used to traverse the elements in the forward direction as well as the reverse direction in a LinkedList.
The method hasNext( ) in ListIterator returns true if there are more elements in the LinkedList while traversing in the forward direction and false otherwise. The method next( ) returns the next element in the LinkedList and advances the cursor position.
The method hasPrevious( ) in ListIterator returns true if there are more elements in the LinkedList while traversing in the reverse direction and false otherwise. The method previous( ) returns the previous element in the LinkedList and reduces the cursor position backward.
A program that demonstrates this is given as follows.
Example
import java.util.ListIterator;
import java.util.LinkedList;
public class Demo {
public static void main(String[] args) {
LinkedList<String> l = new LinkedList<String>();
l.add("Andy");
l.add("Sara");
l.add("James");
l.add("Betty");
l.add("Bruce");
ListIterator li = l.listIterator();
System.out.println("The LinkedList elements in the forward direction are: ");
while (li.hasNext()) {
System.out.println(li.next());
}
System.out.println("\nThe LinkedList elements in the reverse direction are: ");
while (li.hasPrevious()) {
System.out.println(li.previous());
}
}
}
Output
The output of the above program is as follows −
The LinkedList elements in the forward direction are: Andy Sara James Betty Bruce The LinkedList elements in the reverse direction are: Bruce Betty James Sara Andy
Now let us understand the above program.
The LinkedList is created and LinkedList.add() is used to add the elements to the LinkedList. A code snippet which demonstrates this is as follows
LinkedList<String> l = new LinkedList<String>();
l.add("Andy");
l.add("Sara");
l.add("James");
l.add("Betty");
l.add("Bruce");
Then the ListIterator interface is used to display the LinkedList elements in the forward and reverse direction. A code snippet which demonstrates this is as follows
ListIterator li = l.listIterator();
System.out.println("The LinkedList elements in the forward direction are: ");
while (li.hasNext()) {
System.out.println(li.next());
}
System.out.println("\nThe LinkedList elements in the reverse direction are: ");
while (li.hasPrevious()) {
System.out.println(li.previous());
}