Java ArrayList forEach()

The Java ArrayList forEach() method performs the specified action on each element of the arraylist one by one.

The syntax of the forEach() method is:

arraylist.forEach(Consumer<E> action)

Here, arraylist is an object of the ArrayList class.

forEach() Parameters

The forEach() method takes a single parameter.

  • action - actions to be performed on each element of the arraylist

forEach() Return Value

The forEach() method does not return any value.

Example: Java ArrayList forEach()

import java.util.ArrayList;

class Main {
    public static void main(String[] args) {
        // create an ArrayList
        ArrayList<Integer> numbers = new ArrayList<>();

        // add elements to the ArrayList
        System.out.println("ArrayList: " + numbers);

        // multiply 10 to all elements
        System.out.print("Updated ArrayList: ");
        // pass lambda expression to forEach()
        numbers.forEach((e) -> {
          e = e * 10;
          System.out.print(e + " ");


ArrayList: [1, 2, 3, 4]
Updated ArrayList: 10 20 30 40 

In the above example, we have created an arraylist named numbers. Notice the code,

numbers.forEach((e) -> {
  e = e * 10;
  System.out.print(e + " ");  

Here, we have passed the lambda expression as an argument to the forEach() method. The lambda expression multiplies each element of the arraylist by 10 and print the resultant value.

To learn more about lambda expression, visit Java Lambda Expressions.

Note: The forEach() method is not the same as the for-each loop. We can use the Java for-each loop to iterate through each element of the arraylist.