In this post under Java, I will show with example how to iterate a list in both directions.
For iterating in both direction, we will take the help of “ListIterator” class.
We get an instance of “ListIterator” by calling “listIterator” method on a list.
Below is the code snippet, where “integerList” is a list of type parameter “Integer”
ListIterator<Integer> listIterator = integerList.listIterator();
Once we obtain an instance of “ListIterator” we can use “hasNext” and “next” methods to move forward one item at a time.
We can also use “hasPrevious” and “previous” methods to move backward one item at a time.
Below is the complete main class for your reference.
Main class
1 package core.collection;
2
3 import java.util.ArrayList;
4 import java.util.List;
5 import java.util.ListIterator;
6
7 public class ListIteratorDemo {
8 public static void main(String[] args) {
9 List<Integer> integerList = new ArrayList<>(0);
10 integerList.add(1);
11 integerList.add(2);
12 integerList.add(3);
13 integerList.add(4);
14 integerList.add(5);
15 integerList.add(6);
16 integerList.add(7);
17 integerList.add(8);
18 integerList.add(9);
19 integerList.add(10);
20
21 ListIterator<Integer> listIterator = integerList.listIterator();
22 System.out.println("Iterating forward");
23 while(listIterator.hasNext()) {
24 int data = listIterator.next();
25 System.out.print(data + ",");
26 }
27 System.out.println();
28 System.out.println("Iterating backward");
29 while(listIterator.hasPrevious()) {
30 int data = listIterator.previous();
31 System.out.print(data + ",");
32 }
33 }
34 }
In the above code, at line 9 I create a list of type parameter “Integer” named “integerList” and populated it.
At line 21, I obtain an instance of “ListIterator” by calling “listIterator” method on the “integerList”.
In the loop at line 23, I move forward using “hasNext” and “next” method and print the elements.
Similarly in the loop at line 29, I move backward using “hasPrevious” and “previous” method and print the elements.
In this way we can iterate a list in both directions.