Passing lambda expression in Method

Lambda expression can be passed as an argument. It gives programmer power of passing executable code in method.

Lambda expression can be passed in method which has argument of type of functional interface. for example say interface demo has one abstract method

Example :


 interface demo 
{
int fact(int a);
}

Above interface is a functional interface because there is only one abstract method is there. Lambda expression can be passed in a method which argument's type is interface demo.


Example :


 int CalculateFact(demo d,int n);
  

In above method type of first argument is demo, which is functional parameter. So lambda expression can be passed as first argument.


Important ! To pass a lambda expression as an argument, the type of the parameter receiving the lambda expression argument must be of a functional interface type compatible with the lambda.

Example: passing lambda expression as an argument


// Functional interface 
interface check
{
boolean test(int a);
}
// class one defining a static method.
// this method taking two parameter.
// First parameter is type of check and another is int.
// Lambda expression can be passed as first argument.
class one
{
static boolean PerformCheck(check c,int b)
{
return c.test(b);
}
}

class two
{
public static void main(String arg[])
{
// calling static method of class one.
// passing lambda expression as first argument.
// (x)->(x%2)==0 [expression check x is even or not.]
boolean result=one.PerformCheck((x)->(x%2)==0,11);
System.out.println("Result:"+result);
}
}