- What is the Syntax of Lamdba Expression ? Give examples of each.
- Can we use annotations and final modifiers for parameters in Lambda expressions?
- Since Java is statically typed language, it is necessary to specify the type for parameters in lambda expressions?
- In what cases and when can we avoid specifying type for parameters in Lambdas?
- How do you specify type of returned variables in Lambdas?
Syntax of Lambda expressions in Java8 is very similar to writing methods without any return types :
- parameter -> expression
- (parameters) -> {expressions}
- () -> expression
- () -> {expressions}
- (type parameter, type parameter ....) -> expression
- (type parameter, type parameter ....) -> { expressions }
- Never specify the result type of a lambda expression. It is always inferred from the context.
Syntax | Meaning | Example |
---|---|---|
parameter -> expression sasdasdadsadadadadadas | Simplest Lambda expression, the code fits into one expression. A single parameter with inferred type of passed to the lambda expression. The type of parameter is implied in the context. asdasfasdfassdsdfsfsdfsdfsdfsddfsdfasdfasdfafsadfsd | ActionListener acl = event -> System.out.println("Single expression Lamdba");asdasfasdfassdsdfsfsdfsdfsdfsdadfsd |
(parameters) -> {expressions} | Multiple parameters with multiple expressions are often coded inside "( )" and " { } " respectively.The type of parameters is implied in the context. | BinaryOperator<Long> add = (x , y) -> { z = x + y; return z; } Comparator<String> comp = (first, second) -> Integer.compare( first.length(), second.length() ) |
() -> expression | Lambda that requires no parameters , one still provides an empty parenthesis | Runnable myRun = () -> System.out.println("Running a runnable's RUN !!") |
() -> {expressions} | Lambda has no parameters but performs a bunch of tasks/multiple expressions | () -> { for ( int i = 0; i <10 ; i++ ) { new Thread(myRun).start(); }} |
(type parameter, type parameter ....) -> expression | When the type of parameters are not implied in the context, we need to supply the type with the parameter. | |
(type parameter, type parameter ....) -> { expressions } | Same meaning as above, but with more number of expressions. | |
No return type for lambda | The result type of lambda expression is always inferred from the context | (first, second) -> Integer.compare(first.length(), second.length()) The above example is used in context where the result type is int. |
(annotations type parameter) -> expression | Just like method parameters, you can add annotations to lambda parameters | (@NonNull String name) -> .... |
(final type parameter) -> expression | Similarly, one can add final modifier to typed parameter in Lambda expressions | (final String name) -> .... |
No comments:
Post a Comment