Can you do a forEach loop on an ArrayList?
Java ArrayList forEach()In this tutorial, we will learn about the Java ArrayList forEach() method with the help of examples. Show The forEach() method performs the specified action on each element of the arraylist one by one. Exampleimport java.util.ArrayList; class Main { public static void main(String[] args) { // create an ArrayList ArrayList numbers.forEach((e) -> {
e = e * 10;
System.out.print(e + " ");
});
}
}
// Output: ArrayList: [1, 2, 3, 4]
// Updated ArrayList: 10, 20, 30, 40Syntax of ArrayList forEach()The syntax of the forEach() method is: Here, arraylist is an object of the ArrayList class. forEach() ParametersThe forEach() method takes a single parameter.
forEach() Return ValueThe forEach() method does not return any value. Example: Java ArrayList forEach()import java.util.ArrayList; class Main { public static void main(String[] args) { // create an ArrayList ArrayList numbers.forEach((e) -> {
e = e * e;
System.out.print(e + " ");
});
}
}Output ArrayList: [3, 4, 5, 6] Updated ArrayList: 9 16 25 36In the above example, we have created an arraylist named numbers. Notice the code, numbers.forEach((e) -> { e = e * e; System.out.print(e + " "); });Here, we have passed the lambda expression as an argument to the forEach() method. The lambda expression multiplies each element of the arraylist by itself and prints the resultant value. To learn more about lambda expressions, visit Java Lambda Expressions. Note: The forEach() method is not the same as the for-each loop. We can use the Java for-each loop to iterate through each element of the arraylist. |