Iterate through List in Java

Lists in Java allow us to maintain an ordered collection of objects. Duplicate elements as well as null elements can also be stored in a List in Java. The List interface is a part of java.util package and it inherits the Collection interface. It preserves the order of insertion.

There are several ways to iterate over List in Java. They are discussed below:

Methods:

  1. Using loops (Naive Approach)
  2. Using Iterator
  3. Using List iterator
  4. Using lambda expression
  5. Using stream.forEach()
  6. Using Spliterator (Java 8 and later)

Method 1-A: Simple for loop

Each element can be accessed by iteration using a simple for loop. The index can be accessed using the index as a loop variable.

Syntax:

for (i = 0; i < list_name.size(); i++) 
{
  // code block to be executed
}

Below is an example of this method:

Java
// Java Program to iterate over List
// Using simple for loop

// Importing all classes of
// java.util package
import java.util.*;

// CLass
class GFG {

    // Main driver method
    public static void main(String args[])
    {
        // Creating a ArrayList
        List<String> myList = new ArrayList<String>();

        // Adding elements to the list
        // Custom inputs
        myList.add("A");
        myList.add("B");
        myList.add("C");
        myList.add("D");

        // For loop for iterating over the List
        for (int i = 0; i < myList.size(); i++) {

            // Print all elements of List
            System.out.println(myList.get(i));
        }
    }
}

Output
A
B
C
D

Complexity of the above Method:

Time Complexity: O(n), where ‘n’ is the size of the list.
Auxiliary Space: O(1), Constant space is used for loop variables (i in this case).

Method 1-B: Enhanced for loop

Each element can be accessed by iteration using an enhanced for loop. This loop was introduced in J2SE 5.0. It is an alternative approach to traverse the for a loop. It makes the code more readable.

Syntax:

for(data_type variable : List_name)
{  
 // Body of the loop. 
 // Each element can be accessed using variable.  
}

Below is the example of this method:

Java
// Java Program to Iterate over a List
// using enhanced for loop (for-each)

// Importing all classes of
// java.util package
import java.util.*;

// Class
class GFG {

    // Main driver method
    public static void main(String args[])
    {
        // Creating an Arraylist
        List<String> myList = new ArrayList<String>();

        // Adding elements to the List
        // Custom inputs
        myList.add("A");
        myList.add("B");
        myList.add("C");
        myList.add("D");

        // Using enhanced for loop(for-each) for iteration
        for (String i : myList) {

            // Print all elements of ArrayList
            System.out.println(i);
        }
    }
}

Output
A
B
C
D

Complexity of the above Method:

Time Complexity: O(n), where ‘n’ is the size of the list.
Auxiliary Space: O(1), Constant space is used for loop variables (i in this case).

Method 1-C: Using a while loop

Iterating over a list can also be achieved using a while loop. The block of code inside the loop executes until the condition is true. A loop variable can be used as an index to access each element.

Syntax:

while(variable<list_name.size())
{
   // Block of code to be executed 
}

Below is the example of this method:

Java
// Java Program to iterate over a List
// using while loop

// Importing all classes of
// java.util package
import java.util.*;

// Class
class GFG {

    // Main driver method
    public static void main(String args[])
    {
        // Creating an ArrayList
        List<String> myList = new ArrayList<String>();

        // Adding elements to the List
        // Custom inputs
        myList.add("A");
        myList.add("B");
        myList.add("C");
        myList.add("D");

        // Initializing any variable to 0
        int i = 0;

        // If variable value is lesser than
        // value indicating size of List
        while (i < myList.size()) {

            // Print element of list
            System.out.println(myList.get(i));

            // Increase variable count by 1
            i++;
        }
    }
}

Output
A
B
C
D

Complexity of the above Method:

Time Complexity: O(n), where ‘n’ is the size of the list.
Auxiliary Space: O(1), Constant space is used for loop variables (i in this case).

Method 2: Using iterator

An iterator is an object in Java that allows iterating over elements of a collection. Each element in the list can be accessed using iterator with a while loop.

Syntax:

Iterator<data_type> variable = list_name.iterator();

Below is the example of this method:

Java
// Java Program to iterate over the list
// using iterator

// Importing all classes of
// java.util package
import java.util.*;

// Class
class GFG {

    // Main driver method
    public static void main(String args[])
    {
        // Creating an ArrayList
        List<String> myList = new ArrayList<String>();

        // Adding elements to the List
        // Custom inputs
        myList.add("A");
        myList.add("B");
        myList.add("C");
        myList.add("D");

        // Iterator
        Iterator<String> it = myList.iterator();

        // Condition check for elements in List
        // using hasNext() method returning true till
        // there is single element in a List
        while (it.hasNext()) {

            // Print all elements of List
            System.out.println(it.next());
        }
    }
}

Output
A
B
C
D

Complexity of the above Method:

Time Complexity: O(n), where ‘n’ is the size of the list.
Auxiliary Space: O(1), Constant space is used for loop variables (i in this case).

Method 3: Using List iterator

ListIterator is an iterator in Java which is available since the 1.2 version. It allows us to iterate elements one-by-one from a List implemented object. It is used to iterator over a list using while loop.

Syntax:

ListIterator<data_type> variable = list_name.listIterator();

Below is the example of this method:

Java
// Java program to iterate over a list
// using ListIterator
import java.util.*;

// Class
class GFG {

    // Main driver method
    public static void main(String args[])
    {
        // Creating an ArrayList
        List<String> myList = new ArrayList<String>();

        // Adding elements to the List
        // Custom inputs
        myList.add("A");
        myList.add("B");
        myList.add("C");
        myList.add("D");

        // List iterator
        ListIterator<String> it = myList.listIterator();

        // Condition check whether there is element in List
        // using hasNext() which holds true till
        // there is single element in List
        while (it.hasNext()) {

            // Print all elements of List
            System.out.println(it.next());
        }
    }
}

Output
A
B
C
D

Complexity of the above Method:

Time Complexity: O(n), where ‘n’ is the size of the list.
Auxiliary Space: O(1), Constant space is used for loop variables (i in this case).

Method 4: Using Iterable.forEach()

This feature is available since Java 8. It can also be used to iterate over a List. Iteration can be done using a lambda expression.

Syntax:

list_name.forEach(variable->{//block of code})

Below is the example of this method:

Java
// Java Program to iterate over a List
// using forEach()

// Importing all classes of
// java.util method
import java.util.*;

// Class
class GFG {

    // Main driver method
    public static void main(String args[])
    {
        // Creating an ArrayList
        List<String> myList = new ArrayList<String>();

        // Adding elements to the List
        // Custom inputs
        myList.add("A");
        myList.add("B");
        myList.add("C");
        myList.add("D");

        // Lambda expression printing all elements in a List
        myList.forEach(
            (temp) -> { System.out.println(temp); });
    }
}

Output
A
B
C
D

Complexity of the above Method:

Time Complexity: O(n), where ‘n’ is the size of the list.
Auxiliary Space: O(1), Constant space is used for loop variables (i in this case).

Method 5: Using Stream.forEach()

The processing order of stream().forEach() is undefined while in case of forEach(), it is defined. Both can be used to iterate over a List.

Syntax:

list_name.stream.forEach(variable->{//block of code})

Below is the example of this method:

Java
// Java Program iterating over a List
// using stream.forEach() method

// Importing all classes of
// java.util method
import java.util.*;

// Class
class GFG {

    // Main driver method
    public static void main(String args[])
    {
        // Creating an ArrayList
        List<String> myList = new ArrayList<String>();

        // Adding elements to the List
        // Custom inputs
        myList.add("A");
        myList.add("B");
        myList.add("C");
        myList.add("D");

        // stream.forEach() method prints
        // all elements inside a List
        myList.stream().forEach(
            (temp) -> System.out.println(temp));
    }
}

Output
A
B
C
D

Complexity of the above Method:

Time Complexity: O(n), where ‘n’ is the size of the list.
Auxiliary Space: O(1), Constant space is used for loop variables (i in this case).

Methods 6: Using Spliterator (Java 8 and later)

Java 8 introduced the Spliterator interface, which stands for “split iterator.” It provides a way to iterate over elements in a more parallel-friendly manner. A Spliterator can be obtained from various sources, including collections like lists. The forEachRemaining method of Spliterator is used to traverse all remaining elements sequentially.

Syntax:

Spliterator<String> spliterator = myList.spliterator();

Below is the example of this method:

Java
// Java Program iterating over a List
// using Spliterator
import java.util.List;
import java.util.Spliterator;

public class ListIteration {
    public static void main(String[] args) {
        // List of String
          List<String> myList = List.of("A", "B", "C","D");
      
        // Using Spliterator
        Spliterator<String> spliterator = myList.spliterator();
        spliterator.forEachRemaining(System.out::println);
    }
}

Output
A
B
C
D

Complexity of the above Method:

Time Complexity: O(n), where ‘n’ is the size of the list.
Auxiliary Space: O(log n) or O(1), (depending on the characteristics of the Spliterator implementation)