How an iterator object can be used to iterate a list in Java?


The List interface extends Collection interface and represents a collection storing a sequence of elements. User of a list has quite precise control over where an element to be inserted in the List. These elements are accessible by their index and are searchable. ArrayList is the most popular implementation of the List interface among the Java developers.

List interface provides two types of iterator objects. First one is Iterator and second one is ListIterator. In this article, we're going to discuss both types of iterator with corresponding examples.

iterator() method

iterator() method returns an Iterator to iterate the list of elements.

Iterator<E> iterator()

Returns an iterator over the elements in this list in proper sequence.

The following code snippet shows the use of iterator.

Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()) {
   System.out.print(iterator.next() + " ");
}

listIterator() method

listIterator() method returns a more flexible iterator. It allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides.

ListIterator<E> listIterator()

The following code snippet shows the use of listIterator.Use listIterator from the list to iterate through its elements.

ListIterator<Integer> iterator = list.listIterator();
while(iterator.hasNext()) {
   System.out.print(iterator.next() + " ");
}

Example 1

Following is the example showing the use of iterator() method to iterate the list −

package com.tutorialspoint;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class CollectionsDemo {
   public static void main(String[] args) {
      List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,5));
      Iterator<Integer> iterator = list.iterator();
      while(iterator.hasNext()) {
         System.out.print(iterator.next() + " ");
      }
   }
}

Output

This will produce the following result −

1 2 3 4 5

Example 2

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) {
      List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,5));
      ListIterator<Integer> iterator = list.listIterator();
      while(iterator.hasNext()) {
         System.out.print(iterator.next() + " ");
      }
   }
}

Output

This will produce the following result −

1 2 3 4 5

Updated on: 26-May-2022

129 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements