- Iterate through List using Regular for loop
- Iterate through List using Enhanced for loop
- Iterate through List using forEach method
- Iterate through List using Iterator
- Iterate through List using a while loop
Below is an example code to loop through List using regular for loop.
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));
}
}
-
The enhanced for 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 regular for loop.
-
Enhanced for loop syntax looks like this, for (Object obj : list) { }, here Object obj is the element type which the list holds.
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);
}
}
-
Starting from Java 8, we can use forEach method to iterate through List elements,
which takes a java.util.function.Consumer as argument,
in below example we are passing consumer function as lambda expression.
-
java.util.function.Consumer is a functional interface, it provides target types for lambda expressions and method references.
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();
}
}
-
In the above code, we are passing a method reference System.out.println(String str)
that takes String as input, using the syntax System.out::println.
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.
-
If you want to pass list's elements to your method, you can simply pass that method reference using the syntax shown below.
groceries.forEach(new IterateThroughListUsingLambda()::print);
-
You can also implement inline method implementation and consume list's elements using a lambda function,
item -> { } 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.
groceries.forEach(item -> {
System.out.println("inside inline function : " +item);
});
Iterator
-
List interface has two methods that we can use for iteration,
iterator() that returns java.util.Iterator and listIterator() which returns
java.util.ListIterator. ListIterator extends Iterator, so for the below example we can use either.
Difference between these two is explained here, Iterator vs ListIterator.
-
Iterator works such a way that it creates a cursor pointing to the first element and then traverse through the end.
hasNext() method of Iterator returns true if the current position is not the end of list
and next() method of Iterator will return the current element and move cursor to next element.
-
You can use Iterator in while loop as well as for loop, both are shown below.
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();
}
}
You can loop through elements of List using a while with a condition that checks
whether we reach end of list or not. In below example we are using an integer counter to check end of loop.
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++));
}
}
Similar Articles
-
How to remove elements from a List
-
How to remove elements from a List while iterating