Lambda Expressions
In this tutorial, we will learn about what are Lambda expressions and how to use lambda expressions in Java.
Java lambda expressions are Java’s first step into functional programming. Lambda calculus is a big change in the mathematical world which has been introduced in 1930. Because of the benefits of Lambda calculus slowly these concepts started using in the programming world. “LISP” is the first programming that uses Lambda Expression.
The other languages which use lambda expressions are:
- C#.Net
- C Objective
- C
- C++
- Python
- Ruby etc.
and finally in Java also.
The Main Objective of Lambda Expression is to bring the benefits of functional programming into Java.
What is Lambda Expression?
A lambda expression is a new and important feature of Java that 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 is also known as anonymous functions or closures.
E.g
public void add(inta, int b) {
System.out.println(a+b);
}
We can write the 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 the 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 the type of parameter. If the compiler expects the type based on the context then we can remove the type. i.e., the 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 are present then these parameters should be separated with a comma (,).
4. If a zero number of parameters is available then we have to use an 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 the 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 is present then curly braces are optional.
7. Once we write a lambda expression we can call that expression just like a method, for this functional interfaces are required.
That’s all about the Lambda Expressions in Java. If you have any queries or feedback, please write us at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!!