Java - Collection Framework ListIterator

Introduction

ListIterator interface inherits the Iterator interface.

It can access to elements in the list from the current position in the backward direction.

You can get a list iterator for all elements of the list or a sublist, like so:

List<String> list = new ArrayList<>();

// Populate the list here...

// Get a full list iterator
ListIterator<String> fullIterator = list.listIterator();

// Get a list iterator, which will start at index 5 in the forward direction.
ListIterator<String> partialIterator = list.listIterator(5);

The hasPrevious() method of the ListIterator returns true if there is an element before the current position in the list iterator.

To get the previous element, use its previous() method.

You can also get to the index of the next and previous element from the current position using its nextIndex() and previousIndex() methods.

It has methods to insert, replace, and remove an element at the current location.

The following code uses a ListIterator.

It iterates over elements of a List, first in the forward direction and then in the backward direction.

You do not need to recreate the ListIterator again to iterate in the backward direction.

Demo

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class Main {
  public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    list.add("XML");
    list.add("Javascript");
    list.add("Json");
    list.add("Java");

    System.out.println("List: " + list);

    // Get the list iterator
    ListIterator<String> iterator = list.listIterator();

    System.out.println();//from   ww w . j  av a  2 s.  co m
    System.out.println("List Iterator in forward direction:");
    while (iterator.hasNext()) {
      int index = iterator.nextIndex();
      String element = iterator.next();
      System.out.println("Index=" + index + ", Element=" + element);
    }

    System.out.println();
    System.out.println("List Iterator in backward direction:");

    // Reuse the iterator to iterate from the end to the beginning
    while (iterator.hasPrevious()) {
      int index = iterator.previousIndex();
      String element = iterator.previous();
      System.out.println("Index=" + index + ", Element=" + element);
    }
  }
}

Result