ListIterator

Java ListIterator interface is a member of the Java Collection Framework. Java ListIterator interface extends the Iterator interface and it allows us to iterate the list in either direction i.e. forward and backward directions.

Unlike Enumeration, Iterator and ListIterator allows us to remove elements from underlying collection while iterating over the elements of the collection.

Java Iterator defines the below given methods.
1) The hasNext method returns boolean depending upon whether there are more elements to iterator over in the collection in forward direction.
2) The next method returns the next element of the collection and increment the cursor position.
3) The hasPrevious method returns boolean depending upon whether there are more elements to iterate over in the collection in reverse direction.
4) The previous method returns the previous element of the collection and decrements the cursor position.
5) The remove method removes the current element located at the cursor position from the underlying collection.
6) The nextIndex method returns the index of the element that will be returned by the subsequent call to the next method.
7) The previousIndex method returns the index of the element that will be returned by the subsequent call to the previous method.
8) The set method replaces the element at the cursor position by specified element.
9) The add method inserts the specified element at the cursor position.

The listIterator method is used to get ListIterator object for the collection class like implementations of Set and List interface.

Here is how to iterator over a collection using ListIterator in forward or reverse direction.
1) Get the ListIterator object for the collection by calling the listIterator method.
2) Loop until ListIterator object’s hasNext method returns true.
3) Inside the loop, call next method of the ListIterator object to get the current element of collection.
4) To iterate over a collection in the backward direction, use hasPrevious and previous methods of the ListIterator instead of the hasNext and next methods.

Below given are some of the Java ListIterator examples which shows how to use ListIterator in Java.

Java ListIterator Examples

Join 1000+ fellow learners! Enter your email address below: