Recent Posts

Saturday, 6 October 2018

Lambda Expressions Tutorial

     In this tutorial we will learn about what is Lambda expression and how to use lambda expressions in Java.

     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 other languages which uses lambda expressions are:
1. C#.Net
2. C Objective
3. C
4. C++
5. Python
6. Ruby etc.
and finally in Java also.
     The Main Objective of Lambda Expression is to bring benefits of functional programming into Java.

What is Lambda Expression?
     Lambda expression is a new and important feature of Java which was included in Java SE 8. 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.
E.g 
 public void add(inta, int b) {
   System.out.println(a+b);
}
We can write above code in lambda expression as follows
(int a, int b) -> System.out.println(a+b);
     If the type of the parameter can be decided by compiler automatically based on the context then we can remove types also.
The above Lambda expression we can rewrite as
(a, b) -> System.out.println(a+b);
Note
1. A lambda expression can have zero or more number of parameters (arguments).
()-> System.out.println("Hi this is Ashok");
(int a) -> System.out.println(a);
(int a, int b) -> System.out.println(a+b);
2. Usually we can specify type of parameter. If the compiler expects the type based on the context then we can remove type. i.e., programmer is not required.
(int a, int b) -> System.out.println(a+b);
written as
(a, b) -> System.out.println(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 ()].
5. If only one parameter is available and if the compiler can expect the type then we can remove the type and parenthesis also.
(int a) -> System.out.println(a);
(a) -> System.out.println(a);
a -> System.out.println(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.
7. Once we write lambda expression we can call that expression just like a method, for this functional interfaces are required.


Next Functional Interfaces
 

No comments:

Post a Comment