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.

  1. A lambda expression can have zero, one or more parameters.
  2. The type of the parameters can be explicitly declared or it can be inferred from the context.
  3. Multiple parameters are enclosed in mandatory parentheses and separated by commas. Empty parentheses are used to represent an empty set of parameters.
  4. When there is a single parameter, if its type is inferred, it is not mandatory to use parentheses. e.g. a -> return a*a.
  5. The body of the lambda expressions can contain zero, one or more statements.
  6. 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");