Lambda Expression
just an anonymous function, i.e., a function without name ,without return type and without modifiers. They are written exactly in the place where it’s needed, typically as a parameter to some other function.
- A lambda expression can have zero, one or more parameters.
- The type of the parameters can be explicitly declared or it can be inferred from the context.
- Multiple parameters are enclosed in mandatory parentheses and separated by commas. Empty parentheses are used to represent an empty set of parameters.
- When there is a single parameter, if its type is inferred, it is not mandatory to use parentheses. e.g. a -> return a*a.
- The body of the lambda expressions can contain zero, one or more statements.
- If body of lambda expression has single statement curly brackets are not mandatory and the return type of the anonymous function is the same as that of the body expression. When there is more than one statement in body than these must be enclosed in curly brackets.
No Parameter Syntax | One Parameter Syntax | Two Parameter Syntax |
() -> System.out.println("No Parameter"); |
(p1) ->System.out.println("One Parameter"); |
(p1,p2) -> System.out.println("Two Parameter"); |
No Comments Yet!!