ListIterator in Java


Java Java ListViews 1186

ListIterator in Java is an interface that we use to navigate through a List collection in both directions. It extends the Iterator interface that we have learned in the previous tutorial. In this tutorial, we will discuss Java ListIterator with detailed examples.

Java ListIterator

Java ListIterator interface was available from JDK 1.2. We can use the ListIterator to iterate through any type of List Collection like List, ArrayList, or LinkedList. It extends the Iterator. We can use the ListIterator to navigate in both forward and backward directions. We can also use it to read, add, update, and delete operations. To use the ListIterator interface, we need to import the java.util.ListIterator package.

Java ListIterator

Java ListIterator methods

Below are the methods that the ListIterator supports.

MethodDescriptionParameter
void add(Object e)Adds an element to the list either before the element returned by the next() method or after the element returned by the previous() methode - element to be inserted
boolean hasNext()Returns true if there are more elements to traverse in the forward direction
boolean hasPrevious()Returns true if there are more elements to traverse in the reverse direction
Object next()Returns the next element in the list while traversing in the forward direction.
int nextIndex()Returns the index of the next element
Object previous()Returns the previous element while traversing the list in the reverse direction.
int previousIndex()Returns the index of the previous element while traversing in the reverse direction
void remove()Removes the element returned by the next() method or the previous() method.
void set(Object e)Replaces the element returned by either next() or previous() with the specified element.To use this method, neither add() nor remove() should have been called after the next() or previous() methods.e - the element to be replaced

Working of ListIterator

Below are the steps that describe the working of a Java ListIterator.

  • Create a ListIterator object using any of the List Collections. Eg: ListIterator<String> iterator_variable = list_variable.listiterator();
  • To traverse in the forward direction, we use the hasNext() method within the while loop to check if there are more elements in the list.
  • If the condition in the above is true, we can access the element using the next() method.
  • To traverse in the backward direction, we use the hasPrevious() method within the while loop to check if there are elements in the list.
  • If the above condition is true, we can access the element using the previous() method.
  • To access the index of the element in the forward and backward direction, we can use the nextIndex() and the previousIndex() methods.

Example of ListIterator

In the below example, we are demonstrating the usage of various Java ListIterator methods. To navigate in the forward direction, we use the hasNext method until the condition returns false and use the next method to access the element in the ArrayList. To get the index value, we use the nextIndex method. The range starts at 1. The last element index value will be the size of the list, in this case, it is 4.

To navigate in the reverse direction, we use the hasPrevious until the condition returns false. To retrieve the element, we use the previous method, and to get the index value, we use the previousIndex . The range starts from -1 which means the first index value is -1 and the last element value is size-2.

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

public class ListIteratorDemo {

  public static void main(String[] args) {
    ArrayList<String> states = new ArrayList<String>();
    states.add("Delhi");
    states.add("Karnataka");
    states.add("TamilNadu");
    states.add("Hyderabad");
    
    ListIterator l = states.listIterator();
    System.out.println("Forward direction:");
    while(l.hasNext())
      System.out.println("Value: " + l.next() + " Index: " + l.nextIndex());
    
    System.out.println("Reverse direction:");
    while(l.hasPrevious())
      System.out.println("Value: " + l.previous() + " Index: " + l.previousIndex());
  }

}
Forward direction:
Value: Delhi Index: 1
Value: Karnataka Index: 2
Value: TamilNadu Index: 3
Value: Hyderabad Index: 4
Reverse direction:
Value: Hyderabad Index: 2
Value: TamilNadu Index: 1
Value: Karnataka Index: 0
Value: Delhi Index: -1

Example: Add and set methods of ListIterator in Java

Below is an example of using add and set methods of ListIterator. When we use the add()method, it inserts the new value before the next() method call. Hence it inserts the value “Kerala” as the first position. When we call the set() method, it updates the value of the last next() method called. In this case, it replaces the value “Hyderabad” with “Maharashtra”.

We can get these values either by navigating in the reverse direction or printing the ArrayList variable.

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

public class ListIteratorDemo {

  public static void main(String[] args) {
    ArrayList<String> states = new ArrayList<String>();
    states.add("Delhi");
    states.add("Karnataka");
    states.add("TamilNadu");
    states.add("Hyderabad");
    
    ListIterator<String> l = states.listIterator();
    System.out.println("Forward direction:");
    l.add("Kerala");
    while(l.hasNext()) {
      System.out.println(l.next());
    }
    l.set("Maharashtra");	
    System.out.println("Updated States List: " + states);
    System.out.println("Reverse direction:");
    while(l.hasPrevious()) {
      System.out.println(l.previous());
    }
  }

}
Forward direction:
Delhi
Karnataka
TamilNadu
Hyderabad
Updated States List: [Kerala, Delhi, Karnataka, TamilNadu, Maharashtra]
Reverse direction:
Maharashtra
TamilNadu
Karnataka
Delhi
Kerala

Example: Remove method of ListIterator in Java

Below is an example of using the remove method in the ListIterator. If the value of the element is 2, we then remove the element. In the updated list, we can see that the value 2 is deleted.

import java.util.ListIterator;
import java.util.LinkedList;

public class RemoveListIterator {

  public static void main(String[] args) {
    LinkedList<Integer> num = new LinkedList<Integer>();
    for(int i=0;i<5;i++)
      num.add(i);
    System.out.println("Original numbers: " + num);
    
    ListIterator<Integer> li = num.listIterator();
    while(li.hasNext()) {
      int val = li.next();
      if(val == 2)
        li.remove();
    }
    System.out.println("List after remove: " + num);

  }

}
Original numbers: [0, 1, 2, 3, 4]
List after remove: [0, 1, 3, 4]

Example: ListIterator with index

We can also specify an index value while using the ListIterator method. This means we can iterate through the elements starting from the index specified. In the below example, we are iterating from index 2. This is the reason that it prints the values from Blue.

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

public class ListIteratorIndex {

  public static void main(String[] args) {
    ArrayList<String> colors = new ArrayList<String>();
    colors.add("Red");
    colors.add("Green");
    colors.add("Blue");
    colors.add("Pink");
    colors.add("Orange");
    
    ListIterator<String> li = colors.listIterator(2);
    System.out.println("Display the values from index 2:");
    while(li.hasNext())
      System.out.println(li.next());

  }

}
Display the values from index 2:
Blue
Pink
Orange

Advantages of ListIterator in Java

  • Allows bidirectional navigation
  • Supports all operations like read, add, update, and delete.
  • Method names are small and easy to understand.

Limitations of ListIterator in Java

Exceptions in ListIterator

Below are the exceptions that can occur while using the Java ListIterator interface:

  • NoSuchElementException – When there are no elements to iterate while using the next() method.
  • UnsupportedOperationException – If the iterator does not support the set() or add() method.
  • ClassCastException – This occurs in the set() or add() method, if the class of the element prevents it to add to the list.
  • IllegalArgumentException – This occurs in the set() or add() method, if some aspect of the element prevents it to add to the list.

Difference between Iterator and ListIterator

IteratorListIterator
It is a universal iteratorIt is not a universal iterator
It can be used for any type of CollectionIt can be used only for List implementation classes
Supports only read and delete operationSupports add, update, read and delete operations.
Can be used only for forward navigationCan be used for forward and reverse direction navigation
It is not a bidirectional iteratorIt is a bidirectional iterator
We use the iterator() methodWe use the listiterator() method.
We cannot specify the index for iterationWe can specify the index for iteration

Reference

Translate ยป