Java 8 introduced lambda expression to move toward functional programming. A lambda expression is an anonymous function that doesn’t have a name and doesn’t belong to any class.
Where to use the Lambda Expression A lambda expression can only be used where the type they are matched against is a single abstract method(SAM) interface or functional interface.
To use a lambda expression, you can either create your own functional interface or use the predefined functional interface provided by Java.
Example of a pre-defined interface: Runnable, callable, ActionListener, etc.
Pre Java 8: Use anonymous inner classes. Post-Java 8: Now use lambda expression instead of anonymous inner classes.
Points to remember Lambda expression is also known as a closure that allows us to treat functionality as a method arguments (passing functions around) or treat code as data. Lambda expression concept was first introduced in the LISP programming language. Lambda expression is used to provide an implementation of a functional interface or Single Method Interface. Lambda expression treated as a function so the compiler does not create .class file. Lambda expression doesn’t need to define a method again for implementation. Lambda expression benefit is less coding. Java Lambda expression Syntax To create a lambda expression, On the left side of the symbol lambda operator(->) specify input parameters (if there are any), and on the right side place the expression or block of statements.
(parameter_list) -> {function_body} For example, the lambda expression (x, y) -> x + y specifies that lambda expression takes two arguments x and y and returns the sum of these.
Note:
Optional type declaration: No need to declare the data type of a parameter. The compiler can inference the data type from the value of the parameter. The optional parenthesis around parameter: No needs to declare a single parameter in parenthesis. For multiple parameters, parentheses are required. Optional curly braces: For a single line of the statement, No need to use curly braces in the expression body. Optional return keyword: The compiler automatically returns the value if the body has a single expression statement to return the value. Curly braces are required to indicate that expression statement returns a value. Here is some Lamda expression example according to a number of arguments.
No Argument Syntax
()->{ //write some statemnet here } One Argument Syntax
(arg1)->{ //write some statemnet here } Two Argument Syntax
(arg1,arg2)->{ //write some statemnet here } Method vs Lambda Expression in Java A function (or method) in Java has four main parts:
A lambda expression has these main parts: Lambda expression only has a parameter list and body.
Related on
Spring boot interview questions and answers
Recommended Posts