Searching...
Saturday, 13 December 2014

Java ListIterator Example

19:01

The ListIterator interface is a special kind of iterator designed to iterate over lists. It provides functionality to iterates a list in both direction. Here is one example to iterate a list in reverse order using ListIterator.

Example

package mycollectiontest;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ListIterator {

public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("One");
list.add("Two");
list.add("Three");
list.add("Four");
list.add("Five");
// Iterator allows only one direction
Iterator<String> it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());

}
// ListIterator allows traversing both direction
java.util.ListIterator<String> listIterator = list.listIterator(list.size());
while (listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
}

}

Output

One
Two
Three
Four
Five
Five
Four
Three
Two
One

0 comments: