java pass lambda as parameter

Lambda is a powerful thing introduced in Java 8 and since it’s launch it has becoming more and more common in use by the Java developers. Major reason behind switching to Java 8 is to get into the Lambda world. In this post, you will learn How to Pass a Lambda as Parameter to another method? 

Pass Lambda as Parameter in Java...!!! Click To Tweet

 

What is Lambda Expression?

A lambda expression is an anonymous method which takes in parameters and returns a value. As it’s just an expression, It doesn’t execute by itself and therefore it’s basically used to implement methods of a Functional Interface.

Few Examples:

 

How to Pass Lambda expression as Method Parameter?

In order to pass Lambda expression as a Method Parameter, the type of method parameter that receives must be of type of the Functional Interface. 

Example: Arithmetic Operations using Lambda Expression

This is the easiest example on how to pass a Lambda as a parameter to another method. 

 

Let’s understand the code:

1. Here we have a functional interface (Arithmetic) which has a method (Operation) that takes two integers and return an integer.

2. Now, let’s create Lambda Expression which takes two integers and return an integer after (adding / Subtracting / Multiplying / Dividing) those two integers. 

3. Finally, Create a static method (Print) that takes Lambda expression as an argument along with two integer values and Implement the method (Operation) of the Interface (Arithmetic) using that Lambda Expression.  

4. Then, just print the values using Sysout operation.

 

Output

java pass lambda as parameter.         java pass lambda as parameter java pass lambda as parameter java pass lambda as parameter java pass lambda as parameter java pass lambda as parameter java pass lambda as parameter pass lambda as parameter java pass lambda as parameter java how to pass lambda as a parameter in java

I hope you understand now, how to pass a Lambda expression as a parameter to another method.

This was the simplest example to make you clear enough on the working of the Lambdas in Java.

java pass lambda as parameter

Pass Lambda as Parameter in Java...!!! Click To Tweet

Do you like this Post? – then check my other helpful posts:

 

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester. He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

close

Enjoy this blog? Please spread the word :)

Follow by Email
Twitter