Java Program to pass lambda expression as a method argument

In this example, we will learn to pass lambda expression as the method argument in Java.

Example 1: Define lambda expressions as method parameters

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("swift");
        languages.add("python");
        System.out.println("ArrayList: " + languages);

        // pass lambda expression as parameter to replaceAll() method
        languages.replaceAll(e -> e.toUpperCase());
        System.out.println("Updated ArrayList: " + languages);
    }
}

Output

ArrayList: [java, swift, python]
Updated ArrayList: [JAVA, SWIFT, PYTHON]

In the above example, we have created an arraylist named languages. Notice the line,

languages.replaceAll(e -> e.toUpperCase());

Here, e -> e.toUpperCase() is a lambda expression. It takes all elements of the arraylist and converts them into uppercase.


Example 2: Pass multiline lambda body as function arguments

import java.util.ArrayList;
import java.util.Arrays;

class Main {
  public static void main(String[] args) {

    // create an ArrayList
    ArrayList<String> languages = new ArrayList<>(Arrays.asList("java", "python"));
    System.out.println("ArrayList: " + languages);

    // call the foEach() method
    // pass lambda as argument fo forEach()
    // reverse each element of ArrayList
    System.out.print("Reversed ArrayList: ");
    languages.forEach((e) -> {

      // body of lambda expression
      String result = "";
      for (int i = e.length()-1; i >= 0 ; i--)
      result += e.charAt(i);
      System.out.print(result + ", ");
    });

  }
}

Output

ArrayList: [java, python]
Reversed ArrayList: avaj, nohtyp,

In the above example, we have created an arraylist languages. Notice the line,

    languages.forEach((e) -> {

      // body of lambda expression
      String result = "";
      for (int i = e.length()-1; i >= 0 ; i--)
      result += e.charAt(i);
      System.out.print(result + ", ");
    });

Here, we are passing lambda expression as an argument to the ArrayList forEach() method. The lambda expression will reverse each element of the arraylist.

Leave a Reply