Iterate through List elements
Java Lists can be iterated in several ways, each with different trade-offs. This article covers six approaches: the classic index-based for-loop, the enhanced for-each loop, Iterator, ListIterator (which supports bidirectional traversal and in-place modification), forEach() with a lambda (Java 8+), and the Stream API.
Iterate through List using Regular for loop
The classic for0list.size() - 1IndexOutOfBoundsException
public static void iterateUsingRegularForLoop() {
List<String> groceries = List.of("Tomatoes", "Potato", "Eggplant","Broccoli", "Squash");
for(int i=0; i<groceries.size(); i++) { // regular for loop
System.out.println("#Item : "+ groceries.get(i));
}
}
Iterate through List using Enhanced for loop
-
The enhanced
loop syntax was introduced in Java 5 as simple way to iterate through List's elements. This syntax can be used to iterate from first index to last index if you do not need to know the index of current element. If you need to know the index, you can use regularfor loop.for -
Enhanced
loop syntax looks like this,for , herefor (Object obj : list) { } is the element type which the list holds.Object obj
public static void iterateUsingEnhancedForLoop() {
List<String> groceries = List.of("Tomatoes", "Potato", "Eggplant","Broccoli", "Squash");
for (String item : groceries) { // enhanced for loop syntax
System.out.println("#Item : " + item);
}
}
Iterate through List using forEach method
-
Starting from Java 8, we can use
method to iterate throughforEach elements, which takes aList as argument, in below example we are passing consumer function as lambda expression.java.util.function.Consumer -
In the above code, we are passing a method reference
that takes String as input, using the syntaxSystem.out.println(String str) . So, what it does is, it internally calls the Method we are passing as reference for each of the element in the list, in this just it just prints the items.System.out::println - If you want to pass list's elements to your method, you can simply pass that method reference using the syntax shown below.
-
You can also implement inline method implementation and consume list's elements using a
function,lambda is the lambda expression, here -> is called lambda operator or the arrow operator, it separates the parameter and the body, and { } is the body of lambda function. item is the parameter to lambda function, it is the reference to List element and you can name it as you wish.item -> { }
package io.cscode.collections.list.examples;
import java.util.List;
public class IterateThroughListUsingLambda {
public static void iterateThroughListUsingLambda() {
List<String> groceries = List.of("Tomatoes", "Potato", "Eggplant","Broccoli", "Squash");
//pass a Java method as consumer function that takes List type as input.
//in below line, we are passing System.out.println that takes String as argument
System.out.println("##### simple forEach loop #####");
groceries.forEach(System.out::println);
//You can pass your own method as well
System.out.println("\n##### passing my own method to forEach #####");
groceries.forEach(new IterateThroughListUsingLambda()::print);
//You can implement a Lambda function inline implementation and pass as argument as well.
System.out.println("\n##### inline forEach consumer function #####");
groceries.forEach(item -> {
System.out.println("inside inline function : " +item);
});
}
public void print(String item) {
System.out.println("logging item in my own method : " +item);
}
public static void main(String[] args) {
iterateThroughListUsingLambda();
}
}
groceries.forEach(new IterateThroughListUsingLambda()::print);
groceries.forEach(item -> {
System.out.println("inside inline function : " +item);
});
Iterate through List using Iterator
-
interface has two methods that we can use for iteration,List that returnsiterator() andjava.util.Iterator which returnslistIterator() . ListIterator extends Iterator, so for the below example we can use either. Difference between these two is explained here, Iterator vs ListIterator.java.util.ListIterator -
Iterator works such a way that it creates a cursor pointing to the first element and then traverse through the end.
method of Iterator returns true if the current position is not the end of list andhasNext() method of Iterator will return the current element and move cursor to next element.next() -
You can use Iterator in
loop as well aswhile loop, both are shown below.for
package io.cscode.collections.list.examples;
import java.util.Iterator;
import java.util.List;
public class IterateThroughListUsingIterator {
public static void iterateUsingIterator() {
List<String> groceries = List.of("Tomatoes", "Potato", "Eggplant","Broccoli", "Squash");
//iterator works based on a pointer hasNext() will tell whether it reached end of List or not
// and next() will fetch the element and move pointer to next element if there is any
System.out.println("###### iterator in while loop #####");
Iterator<String> ite = groceries.iterator();
while(ite.hasNext()) {
System.out.println("inside while loop : "+ ite.next());
}
// same above logic can be implemented using while loop as well.
System.out.println("###### iterator in for loop #####");
for(Iterator<String> it = groceries.iterator(); it.hasNext();) {
System.out.println("inside for loop : "+ it.next());
}
}
public static void main(String[] args) {
iterateUsingIterator();
}
}
Iterate through List using a while loop
You can loop through elements of Listwhile
public static void iterateUsingWhileLoop(){
List<String> groceries = List.of("Tomatoes", "Potato", "Eggplant","Broccoli", "Squash");
int counter =0;
while(counter<groceries.size()) {
System.out.println("#Item : " + groceries.get(counter++));
}
}