English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java ArrayList forEach() method is used to perform a specified operation on each element of the arraylist.
The syntax of forEach() method is:
arraylist.forEach(Consumer<E> action)
action - The operation to be performed on each element of the arraylist
The forEach() method does not return any value.
import java.util.ArrayList; class Main { public static void main(String[] args) { //Create ArrayList ArrayList<Integer> numbers = new ArrayList<>(); // Add element to ArrayList numbers.add(1); numbers.add(2); numbers.add(3); numbers.add(4); System.out.println("ArrayList: "); + numbers); // Take10Multiply all elements System.out.print("Updated ArrayList: "); // Pass the lambda expression to forEach()} numbers.forEach((e -> { e = e * 10; System.out.print(e + " "); }); } }
Output Result
ArrayList: [1, 2, 3, 4] Updated ArrayList: 10 20 30 40
In the above example, we created an array list named numbers. Note the code,
numbers.forEach((e -> { e = e * 10; System.out.print(e + " "); });
Here, we pass the lambda expression as a parameter to the forEach() method. The lambda expression will multiply each element of the arraylist by10,Then output the result value.
For more information about lambda expressions, please visitJava Lambda Expressions.
Note: forEach() method and for-Each loop is different. We can useJava for-Each loopTraverse each element of the arraylist.