Wednesday, September 14, 2022

ListIterator in Java

In this post we'll see another way to iterate a List using ListIterator in Java.

Though there is already an iterator provided for the list, which will iterate sequentially through all the elements in a list but it is uni-directional.

List iteration in Java

Iteration of a list

If you are iterating this ArrayList you can only go from left to right. If you have any such requirement where you want to iterate the list in both directions you can use ListIterator. ListIterator in Java provides next() and previous() methods to iterate in both forward and backward directions.


No current element in ListIterator

The interesting point about Listiterator in Java is that it has no current element. Its current cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). An iterator for a list of length n has n+1 possible cursor positions.

ListIterator in Java

Iterating a list using list iterator

Java ListIterator methods summary

Following is the list of methods in the ListIterator class in Java.
  1. add(E e)- Inserts the specified element into the list (optional operation).
  2. hasNext()- Returns true if this list iterator has more elements when traversing the list in the forward direction.
  3. hasPrevious()- Returns true if this list iterator has more elements when traversing the list in the reverse direction.
  4. next()- Returns the next element in the list and advances the cursor position.
  5. nextIndex()- Returns the index of the element that would be returned by a subsequent call to next().
  6. previous()- Returns the previous element in the list and moves the cursor position backwards.
  7. previousIndex()- Returns the index of the element that would be returned by a subsequent call to previous().
  8. remove()- Removes from the list the last element that was returned by next() or previous() (optional operation).
  9. set(E e)- Replaces the last element returned by next() or previous() with the specified element (optional operation).

Note that the remove() and set(object) methods are not defined in terms of the cursor position, they are defined to operate on the last element returned by a call to next() or previous().

ListIterator Java example with list iteration in both directions

public class ListIteratorDemo {
  public static void main(String[] args) {
    List<Integer> numberList = new ArrayList<Integer>();
    ListIterator<Integer> ltr = null;
    numberList.add(25);
    numberList.add(17);
    numberList.add(108);
    numberList.add(76);
    numberList.add(2);
    numberList.add(36);
    ltr = numberList.listIterator();
    //forward iteration
    System.out.println("Iterating list in forward direction");
    while(ltr.hasNext()){
      System.out.println(ltr.next());
    }
    // backward iteration 
    System.out.println("Iterating list in backward direction");
    while(ltr.hasPrevious()){
      System.out.println(ltr.previous());
    }
  }
}

Output

Iterating list in forward direction
25
17
108
76
2
36
Iterating list in backward direction
36
2
76
108
17
25

Here we are first going forward using next() method. When the forward iteration is done cursor is after the last element so we can go backward using previous method() till the start of the list and that's what is done in the code.

Points to note

  • ListIterator in Java provides an add(E e) method which is not there in Iterator. add(E e) inserts the specified element into the list (optional operation). The element is inserted immediately before the element that would be returned by next(), if any, and after the element that would be returned by previous(), if any.
  • ListItearator also provides set method. void set(E e) replaces the last element returned by next() or previous() with the specified element (optional operation). This call can be made only if neither remove() nor add(E) have been called after the last call to next or previous.
  • ListIterator is fail-fast and throws a ConcurrentModificationException if the underlying collection is structurally modified in any way except through the iterator's own remove or add methods.

That's all for this topic ListIterator in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How ArrayList Works Internally in Java
  2. How to Loop or Iterate an Arraylist in Java
  3. How to Sort an ArrayList in Descending Order in Java
  4. Difference Between ArrayList And LinkedList in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. How HashSet Works Internally in Java
  2. Method Reference in Java
  3. Find All Permutations of a Given String Java Program
  4. Synchronization in Java - Synchronized Method And Block
  5. Difference Between Checked And Unchecked Exceptions in Java
  6. Varargs (Variable-length Arguments) in Java
  7. Covariant Return Type in Java
  8. Java Multithreading Interview Questions And Answers

No comments:

Post a Comment