How do you make a list iterator in Java?


We can utilize listIterator() method of List interface, which allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides.

Syntax

ListIterator<E> listIterator()

Returns a list iterator over the elements in this list (in proper sequence).

Example

Following is the example showing the usage of listIterator() method −

package com.tutorialspoint;

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

public class CollectionsDemo {
   public static void main(String[] args) throws CloneNotSupportedException {
      List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,5));
      System.out.println(list);
      ListIterator<Integer> iterator = list.listIterator();

      // Modify the list using listIterator
      while(iterator.hasNext()){
         Integer item = iterator.next();
         iterator.set(item * item);
      }
      System.out.println(list);

      // Removal of element is allowed
      iterator = list.listIterator();
      while(iterator.hasNext()){
         Integer item = iterator.next();
         if(item % 2 == 0) {
            iterator.remove();
         }
      }
      System.out.println(list);

      // Addition of element is allowed
      iterator = list.listIterator();
      while(iterator.hasNext()){
         Integer item = iterator.next();
         if(item % 5 == 0) {
            iterator.add(36);
         }
      }
      System.out.println(list);
   }
}

Output

This will produce the following result −

[1, 2, 3, 4, 5]
[1, 4, 9, 16, 25]
[1, 9, 25]
[1, 9, 25, 36]

Updated on: 10-May-2022

199 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements