Java ArrayList forEach() Method
The forEach() method is used to iterate over each element in the dynamic array and perform a specific action.
The syntax for the forEach() method is:
arraylist.forEach(Consumer<E> action)
Note: arraylist is an object of the ArrayList class.
Parameter Description:
- action - The action to be performed on each element
Return Value
It does not return any 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 + " ");
});
}
}
Executing the above program will output:
ArrayList: [1, 2, 3, 4]
Updated 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 as an argument to the forEach() method. The lambda expression multiplies each element in the dynamic array by 10 and then prints the result.
For more information about lambda expressions, visit Java Lambda Expressions.
Note: The forEach() method is different from the for-each loop. Java for-each is used to iterate over each element in an array.