Lamda Expressions in Java

Java Lambda Expressions

Lambda Expressions were added in Java 8. Lambda expressions are usually passed as parameters to a function. Lambda expressions can be stored in variables if the variable's type is an interface which has only one method. The lambda expression should have the same number of parameters and the same return type as that method.

It is very useful in collection library. It helps to iterate, filter and extract data from collection. Lamda expressions saves a lot of code.Java lambda expression is treated as a function, so compiler does not create .class file.

A lambda expression is characterized by the following syntax.

       parameter -> expression body

Java lambda expression is consisted of three components.

  • Argument-list: It can be empty or non-empty as well.
  • Arrow-token: It is used to link arguments-list and body of expression.
  • Body: It contains expressions and statements for lambda expression.

Following are the important characteristics of a lambda expression.

  • Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.
  • Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.
  • Optional curly braces − No need to use curly braces in expression body if the body contains a single statement.
  • Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value.

No Parameter Syntax

() -> {  

//Body of no parameter lambda  

One Parameter Syntax

(p1) -> {  

//Body of single parameter lambda  

}  

Two Parameter Syntax

(p1,p2) -> {  

//Body of multiple parameter lambda  

}  

Ex 1:

public class Calculator {
public static void main(String[] args) {
Calculater sum = (a,b) -> a + b;
Calculater multiply = (a,b) -> a * b;
calculate(5,7, sum);
calculate(5,7, multiply);
}
public static void calculate(int a,int b, Calculater format) {
int result = format.run(a,b);
System.out.println(result);
}
}
interface Calculater {
int run(int a, int b);
}

Comments