Write a Java Program to pass lambda expression as a method argument

Java Program to pass lambda expression as a method argument

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to pass lambda expression as a method argument
Java Program to pass lambda expression as a method argument

Write a Java Program to pass lambda expression as a method argument

PROGRAM: Java Program to pass lambda expression as a method argument

/*Java Program to pass lambda expression as a method argument*/

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);
}
}

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 + “, “);
});

}
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *