Iterate through List in Java
Last Updated :
03 Jun, 2024
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:
- Using loops (Naive Approach)
- Using Iterator
- Using List iterator
- Using lambda expression
- Using stream.forEach()
- 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));
}
}
}
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);
}
}
}
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++;
}
}
}
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());
}
}
}
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());
}
}
}
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); });
}
}
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));
}
}
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);
}
}
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)
Similar Reads
Iterate List in Java using Loops
In this article, we are going to see how to iterate through a List. In Java, a List is an interface of the Collection framework. List can be of various types such as ArrayList, Stack, LinkedList, and Vector. There are various ways to iterate through a java List but here we will only be discussing ou
7 min read
How to Iterate Through HashTable in Java?
HashTable is an underlying data structure where the insertion order in HashTable is not preserved, and it is based on the hashcode of keys. Duplicates keys are not allowed, but values can be duplicated. Heterogeneous objects are allowed for both keys and values. Value null is not allowed for both ke
8 min read
Java Program to Iterate LinkedHashSet Elements
The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements
3 min read
How to Iterate HashSet in Java?
HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage. It stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code. Methods to It
3 min read
How to Iterate HashMap in Java?
HashMap is a part of Javaâs collection providing the basic implementation of the Map interface of Java by storing the data in (Key, Value) pairs to access them by an index of another type. One object is listed as a key (index) to another object (value). If you try to insert the duplicate key, it wil
5 min read
Iterate a LinkedList in Reverse Order in Java
For traversing a linked list in reverse order we can use Descending Iterator or List Iterator 1. Descending Iterator Syntax: LinkedList<String> linkedlist = new LinkedList<>(); Iterator<String> listIterator = linkedlist.descendingIterator(); Returns: Descending Iterator returns the
2 min read
How to Iterate over a Queue in Java?
Queue is a concept of Linear Data Structure that follows the concept of FIFO(First In First Out). Queues are majorly used to maintain the order of the elements to which they are added. In this article, we will learn to perform Queue Iteration in Java. Queue Iteration Program in JavaSyntax with Examp
1 min read
Initializing a List in Java
The Java.util.List is a child interface of Collection. It is an ordered collection of objects where duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by the ArrayList, LinkedList, Vector, and
7 min read
How to Clone a List in Java?
Given a list in Java, the task is to clone this list. Example: Input: list = ["Geeks", "for", "Geeks"] Output: clonedList = ["Geeks", "for", "Geeks"] Input: list = ["GeeksForGeeks", "A Computer Science", "Portal"] Output: clonedList = ["GeeksForGeeks", "A Computer Science", "Portal"] In Java, there
9 min read
Java Program to Convert List to HashSet
The List interface provides a way to store the ordered collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. The HashSet class permits the null element. The class al
4 min read