"Lambda Expressions in Java are the short block of code that accepts input as parameters and returns a resultant value".
It is same as lambda functions.
In java, it is normally used to create the instances of functional interfaces (A functional interface is an interface with a single abstract method).
Lambda Expressions are recently introduced in Java SE 8.
Functionalities of Lambda Expression : -
- Lambda Expressions implement the only abstract function and therefore implement functional interfaces.
- It enables to treat functionality as a method argument, or code as data.
- With help of Lambda expression, a function that can be created without belonging to any class.
- A lambda expression can be passed around as if it was an object and executed on demand.
Lambda Expression Syntax:-
A lambda expression is written by the following syntax.
parameter -> expression body
Lambda Expression Parameters:-
There are three types of Lambda Expression Parameters are mentioned below:
- Zero Parameter
- Single Parameter
- Multiple Parameters
1. Lambda Expression with Zero parameter
() -> System.out.println("Zero parameter lambda");
Example:
interface HelloService {void sayHello();}
public static void main(String args[]) {HelloService svc1 = ()-> System.out.println("Hello. This is Zero parameter lambda");svc1.sayHello();}
output: Hello. This is Zero parameter lambda
2. Lambda Expression with Single parameter
(p) -> System.out.println("One parameter: " + p);
Example 1:
interface HelloService {void sayHelloWithName(String message);}
public static void main(String args[]) {HelloService svc1 = (String message)-> System.out.println("Hello "+ message +"!!. This is one parameter lambda");svc1.sayHelloWithName("Ramesh");}
output: Hello Ramesh!!. This is one parameter lambda
It is not mandatory to use parentheses in lambda parameters, if the type of that variable can be inferred from the context.
Example 2:
// A Java program to demonstrate simple lambda expressions
class LambdaTest {
public static void main(String args[])
{
// Creating an ArrayList with elements
// {1, 2, 3, 4}
ArrayList<Integer> arrL = new ArrayList<Integer>();
arrL.add(1);
arrL.add(2);
arrL.add(3);
arrL.add(4);
// Using lambda expression to print all elements
// of arrL
arrL.forEach(n -> System.out.println(n));
// Using lambda expression to print even elements
// of arrL
arrL.forEach(n -> {
if (n % 2 == 0)
System.out.println(n);
});
}
}
1
2
3
4
2
4
3. Lambda Expression with Multiple parameters
(p1, p2) -> System.out.println("Multiple parameters: " + p1 + ", " + p2);
A Java program to demonstrate the working of a lambda expression with two arguments.
- public class LambdaTest {
- // operation will be implemented using lambda expressions
- interface MathOperation {
- int operation(int a, int b);
- }
- // sayMessage() will implemented using lambda expressions
- interface GreetingService {
- void sayMessage(String message);
- }
- // Performs MathOperation's operation on 'a' and 'b'
- private int operate(int a, int b, MathOperation fobj)
- {
- return fobj.operation(a, b);
- }
- public static void main(String args[])
- {
- /* lambda expression for addition for two parameters data type for x and y is optional. This expression implements 'MathOperation' interface */
- MathOperation add = (int x, int y) -> x + y;
- // lambda expression multiplication for two
- // parameters This expression also implements
- // 'MathOperation' interface
- MathOperation multiply = (int x, int y) -> {
- System.out.println("hello ");
- return x * y;
- };
- // Creating an object of LambdaTest to call operate //using different implementations using lambda Expressions
- LambdaTest tobj = new LambdaTest();
- // Add two numbers using lambda expression
- System.out.println("Addition is "
- + tobj.operate(6, 3, add));
- // Multiply two numbers using lambda expression
- System.out.println("Multiplication is "
- + tobj.operate(6, 3, multiply));
- // lambda expression for single parameter
- // This expression implements 'GreetingService' interface
- GreetingService fobj = message -> System.out.println("Hello " + message);
- fobj.sayMessage("JavaHubPoint");
- }
- }
Output:
Multiplication is 18
Hello JavaHubPoint
Conclusion:-
Following are the important Conclusions from 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. See line number 41.
- Optional parenthesis around parameter − No need to declare parenthesis for a single parameter. For multiple parameters, parentheses are required. See line number 41.
- Optional curly braces − No need to use curly braces in expression body, if the body contains a single statement. See line number 21. The body of a lambda expression can contain zero, one, or more statements. See line number 26.
- Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. See line number 21.