Lambda Expression
LISP is the 1st lang where lambda expressions came first.
Apart form LISP, C, CPP, PYTHON, SCALA, RUBBY, Objective C
Advantages
- To enable functional programming in java
- To write more readable, maintainable and concise code
- To use APIs very easily and effectively.
- To enable parallel processing
NOTE : Only use in case of functional interface.
Example.
public void display(String str){System.out.println("Hello "+str);}
Using lambda(str)->System.out.println("Hello "+str);orstr->System.out.println("Hello "+str);
int getValue(){
return 5;
}
Using lambda
() -> 5
// concatenating two strings, it has 2 string parameters and they are concatenated in lambda body
(String s1, String s2) -> s1+s2;
Scenarios
(int x, int y) -> x+y; or (x, y) -> x + y; which one of these is a valid lambda expression?
Both of them are valid lambda expressions if used in a correct context.
(int x, y) -> x + y; is this a valid lambda expression?
You can't have lambda expression where type for only one of the parameter is explicitly declared so this lambda expression is invalid.