English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
O método forEach() do Java ArrayList é usado para executar uma operação específica em cada elemento do arraylist.
a sintaxe do método forEach() é:
arraylist.forEach(Consumer<E> ação)
ação - ação a ser executada em cada elemento do arraylist
O método forEach() não retorna nenhum valor.
import java.util.ArrayList; class Main { public static void main(String[] args) { //criar ArrayList ArrayList<Integer> numbers = new ArrayList<>(); // adicionar elementos ao ArrayList numbers.add(1); numbers.add(2); numbers.add(3); numbers.add(4); System.out.println("ArrayList: ", + numbers); // colocar10multiplicar todos os elementos System.out.print("ArrayList atualizada: "); // 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.