Ques 3. What is lambda expression?
Lambda expression is anonymous function which have set of parameters and a lambda (->) and a function body. You can call it function without name.
Structure of Lambda Expressions:
(Argument List) ->{expression;} or
(Argument List) ->{statements;}
For instance, the Runnable interface is a functional interface, so instead of:
Thread thread = new Thread(new Runnable() {
public void run() {
System.out.println("Hello World!");
}
});
Using Lambda you can simply do the following:
Thread thread = new Thread(() -> System.out.println("Hello World!"));
Functional interfaces are usually annotated with the @FunctionalInterface annotation - which is informative and does not affect the semantics.
Ques 4. Can you explain the syntax of Lambda expression?
So we can divide structure of Lambda expression to three parts:
- Arguments
- Array Token
- Statements
1. Argument list or parameters
Lambda expression can have zero or more arguments. First part before '->' is called as argument list or parameters.
()->{System.out.println("Hello")}; //Without argument, will print hello
(int a)->{System.out.println(a)} //; One argument, will print value of a
(int a,int b)-> {a+b};//two argument, will return sum of these two integers
2. Array token (->)
3. Body
- Body can have expression or statements.
- If there is only one statement in body, curly brace is not needed and return type of the anonymous function is same as of body expression.
- If there are more than one statements, then it should be in curly braces and return type of anonymous function is same as value return from code block, void if nothing is returned.