How to iterate List using Iterator in Java?


The List interface extends the Collection interface. It is a collection that stores a sequence of elements. ArrayList is the most popular implementation of the List interface. The 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.

List interface provides an iterator() method which returns an Iterator to iterate the list of elements. The following code snippet shows the use of iterator.

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

There is another but more flexible and powerful iterator available using listIterator() method. The following code snippet shows the use of listIterator.

Use listIterator from the list to iterate through its elements.

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

In this article, we're discussion both iterator methods to iterate a list with corresponding examples.

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

Following is the example showing the use of listIterator() 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> iterator1 = list.listIterator();
      while(iterator1.hasNext()) {
         System.out.print(iterator1.next() + " ");
      }
   }
}

Output

This will produce the following result −

1 2 3 4 5

Updated on: 26-May-2022

421 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements