YouTip LogoYouTip

Java Arraylist Foreach

# Java ArrayList forEach() Method [![Image 3: Java ArrayList](#) Java ArrayList](#) The forEach() method is used to iterate over each element in a dynamic array and perform a specific operation. The syntax for the forEach() method is: arraylist.forEach(Consumer action) **Note:** arraylist is an object of the ArrayList class. **Parameter Description:** * action - The operation to perform 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 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 lambda expression to forEach numbers.forEach((e)->{ e = e *10; System.out.print(e +" "); }); } } The output of the above program is: ArrayList: [1, 2, 3, 4]Updated ArrayList: 10 20 30 40 In the example above, we created a dynamic array named numbers. Note this line: numbers.forEach((e) -> { e = e * 10; System.out.print(e + " "); }); In the example above, we passed an anonymous function lambda expression as a parameter 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, please visit (#) Expressions. **Note:** The forEach() method is different from the for-each loop. (#) is used to iterate over each element in an array. [![Image 4: Java ArrayList](#) Java ArrayList](#)
← Java Arraylist ContainsallPython3 Att Dictionary In Html β†’