Friday 21 September 2018



                                                         Lambda (λ) Expression  Java 8:

Lambda calculus is a big change in mathematical world which has been introduced in 1930. Because of benefits of Lambda calculus slowly this concepts started using in programming world. “LISP” is the first programming which uses Lambda Expression.

The Main Objective of λLambda Expression is to bring benefits of functional programming into java.



What is Lambda Expression (λ):

Lambda Expression is just an anonymous(nameless) function. That means the function which doesn’t have the name,
return type and access modifiers.


Lambda Expression also known as anonymous functions or closures.


Example 1: Normal Java method

public void m1() {
 System.out.println(“Hello Java”);
}

Above Normal Java method, you can write using Lambda Expression (λ) in Following way:

( ) -> {
sop(“Hello Java”);
}
or

( ) -> { sop(“Hello Java”); }
or

() -> sop(“Hello Java”);



Example 2 : Normal Java Method with argument

public void add(int a, int b) {
 System.out.println(a + b);
}
Above Normal Java method you can write using Lambda Expression (λ) in Following way:

(int a, int b) -> sop(a+b);

note 1: If the type of the parameter can be decided by compiler automatically based on the context then we can remove types also.

note 2 : The above Lambda expression we can rewrite as (a,b) -> sop (a+b);




Example 3: Normal Java Method with return

public String m1(String str) {
 return str;
}
Above Normal Java method, you can write using Lambda Expression (λ) in Following way:

(String str) -> return str;
or

(str) -> str;






Conclusions :

1. A lambda expression can have zero or more number of parameters(arguments).
Example:
( ) -> sop(“Hello Java”);
(int a ) -> sop(a);
(inta, int b) -> return a+b;
2. Usually we can specify type of parameter.If the compiler expect the type based on the context then we can remove type.
Example:
(int a, int b) -> sop(a+b);
(a,b) -> sop(a+b);
3. If multiple parameters present then these parameters should be separated with comma(,).
4. If zero number of parameters available then we have to use empty parameter [ like ()].
Example:
( ) -> sop(“Hello Java”);
5. If only one parameter is available and if the compiler can expect the type then we can remove the type and parenthesis also.
example:--
(int a ) -> sop(a);
(a) -> sop(a);
 a->  sop(a);

6. Similar to method body lambda expression body also can contain multiple statements.if more than one statements present then we have
to enclose inside within curly braces. if one statement present then curly braces are optional.

Once we write lambda expression we can call that expression just like a method, for this functional interfaces are required.

No comments:

Post a Comment