Java ArrayList forEach()

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

Example

import java.util.ArrayList;

class Main {
  public static void main(String[] args) {
    // create an ArrayList
    ArrayList<Integer> numbers = new ArrayList<>();
    numbers.add(1);
    numbers.add(2);
    numbers.add(3);
    numbers.add(4);
    System.out.println("ArrayList: " + numbers);

    System.out.print("Updated ArrayList: ");

    // multiply each element by 10
    // using the lambda expression
numbers.forEach((e) -> { e = e * 10; System.out.print(e + " "); });
} } // Output: ArrayList: [1, 2, 3, 4] // Updated ArrayList: 10, 20, 30, 40

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

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
    numbers.add(3);
    numbers.add(4);
    numbers.add(5);
    numbers.add(6);
    System.out.println("ArrayList: " + numbers);

    System.out.print("Updated ArrayList: ");

    // multiply each element by themselves
    // to compute the square of the number
numbers.forEach((e) -> { e = e * e; System.out.print(e + " "); });
} }

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.


Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges