In this tutorial, we will learn about the Java ArrayList forEach() method, and learn how to use this method to execute a set of statements for each element in this ArrayList, with the help of examples.

Java ArrayList forEach() method

ArrayList forEach() performs the given action for each element of this ArrayList until all elements have been processed or the action throws an exception.

Syntax

The syntax of forEach() method is

</>
Copy
ArrayList.forEach(Consumer<? super E> action)

where

ParameterDescription
actionThe action to be performed for each element in the ArrayList.

Returns

The method returns void.

1. forEach(action) – Run a block of code for each element in the ArrayList

In this example, we will define a ArrayList of Strings and initialize it with some elements in it. For each element in this ArrayList, we shall find the string length and print it to the console.

Java Program

</>
Copy
import java.util.ArrayList;
import java.util.Arrays;

public class Example {  
	public static void main(String[] args) {
		ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList("a", "b", "c"));
		arrayList.forEach((n) -> {
			System.out.println(n);
		});
	}  
}

Output

2
3
6

2. forEach(action) – ArrayList of User-defined Objects

In this example, we will define a ArrayList of user-defined class Car and initialize it with some Car objects. We will use ArrayList forEach() method and print the details of each Car object to the console.

Java Program

</>
Copy
import java.util.ArrayList;

public class Example {  
	public static void main(String[] args) {
		ArrayList<Car> arrayList = new ArrayList<Car>();
		arrayList.add(new Car(1, "Tesla"));
		arrayList.add(new Car(2, "BMW"));
		arrayList.add(new Car(3, "Toyota"));
		
		arrayList.forEach((car) -> {
			System.out.println(car.id + " - " + car.name);
		});
    }  
}

class Car {
	int id;
	String name;
	public Car(int id, String name) {
		this.id = id;
		this.name = name;
	}
}

Output

1 - Tesla
2 - BMW
3 - Toyota

Conclusion

In this Java Tutorial, we have learnt the syntax of Java ArrayList forEach() method, and also learnt how to use this method with the help of Java example programs.