Java ArrayList forEach() Method

Java ArrayList Java ArrayList

The forEach() method is used to traverse each element in the dynamic array and perform a specific operation.

The syntax of the forEach() method is:

arraylist.forEach(Consumer<E> action)

Note:arraylist is an object of the ArrayList class.

Parameter Details:

  • action - the operation to be performed on each element

Return Value

No return value.

Example

Multiply all elements by 10:

Example

import java.util.ArrayList;

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

        // Add elements to the array
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);
        System.out.println("ArrayList: " + numbers);

        // Multiply all elements by 10
        System.out.print("Updated ArrayList: ");
       
        // Pass the lambda expression to forEach
        numbers.forEach((e) -> {
            e = e * 10;
            System.out.print(e + " ");
        });
    }
}

Running the above program produces the following output:

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

In the above example, we created a dynamic array named numbers.

Note this line:

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

In the above example, we passed the lambda expression (anonymous function) as a parameter to the forEach() method. The lambda expression multiplies each element in the dynamic array by 10 and then outputs the result.

For more information on lambda expressions, please visitJava Lambdaexpression.

Note:The forEach() method is different from the for-each loop.Java for-eachIt is used to traverse each element in the array.

Java ArrayList Java ArrayList

Other Extensions