How to iterate a Java List using Iterator?

JavaObject Oriented ProgrammingProgramming

The List interface extends the Collection interface and is an important member of Java Collections Framework. List interface declares the behavior of a collection that stores a sequence of elements. The most popular implementation of List interface is ArrayList. 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 provides two methods to efficiently add element in a list.

List interface provides a method iterator() to get an Iterator instance to iterate through its elements and listIterator() method to get a more flexible ListIterator instance which can be used to iterate a list as ListIterator extends Iterator interface.In this article, we're discussing both iterators to iterate a list with corresponding examples.

List.iterator() method example

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

List.listIterator() method example

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

Example 1

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

Output

This will produce the following result −

1 2 3 4 5
raja
Updated on 26-May-2022 13:21:06

Advertisements