Algorithm
-
Initialize ArrayList:
- Create an ArrayList of a specific type (e.g.,
ArrayList<Integer>
).
- Create an ArrayList of a specific type (e.g.,
-
Add Elements to ArrayList:
- Add elements to the ArrayList using the
add
method.
- Add elements to the ArrayList using the
-
Use Lambda Expression for Iteration:
- Use the
forEach
method along with a lambda expression to iterate over the ArrayList. - The lambda expression should specify the action to be performed on each element.
- Use the
-
Lambda Expression Structure:
- The lambda expression structure is
(parameter) -> { /* action */ }
. - In this case, the parameter represents each element in the ArrayList, and the action is what needs to be done with each element.
- The lambda expression structure is
-
Perform Action on Each Element:
- Inside the lambda expression, perform the desired action on each element.
- For example, print the element, manipulate it, or perform any other operation.
-
Complete Iteration:
- The forEach method will automatically iterate over all elements in the ArrayList, applying the lambda expression to each.
Code Examples
#1 Code Example- Pass ArrayList as Function Parameter
Code -
Java Programming
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// create an ArrayList
ArrayList < String> languages = new ArrayList<>();
// add elements to the ArrayList
languages.add("Java");
languages.add("Python");
languages.add("JavaScript");
// print arraylist
System.out.print("ArrayList: ");
// iterate over each element of arraylist
// using forEach() method
languages.forEach((e) -> {
System.out.print(e + ", ");
});
}
}
Copy The Code &
Try With Live Editor
Output
ArrayList: Java, Python, JavaScript,
Demonstration
Java Programing Example to Iterate over ArrayList using Lambda Expression-DevsEnv