Java ArrayList forEach()

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

Example


Syntax of ArrayList forEach()

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()

Output

ArrayList: [3, 4, 5, 6]
Updated ArrayList: 9 16 25 36 

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

numbers.forEach((e) -> {
  e = e * e;
  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 itself and prints the resultant value.

To learn more about lambda expressions, 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.