Algorithm


  1. Initialize ArrayList:

    • Create an ArrayList of a specific type (e.g., ArrayList<Integer>).
  2. Add Elements to ArrayList:

    • Add elements to the ArrayList using the add method.
  3. 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.
  4. 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.
  5. 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.
  6. 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

x
+
cmd
ArrayList: Java, Python, JavaScript,
Advertisements

Demonstration


Java Programing Example to Iterate over ArrayList using Lambda Expression-DevsEnv