Saturday, June 14, 2014

Java 8 : Frequently Asked Questions for Interviews - 4



  1. What  is the Syntax of Lamdba Expression ? Give examples of each.
  2. Can we use annotations and final modifiers for parameters in Lambda expressions?
  3. Since Java is statically typed language, it is necessary to specify the type for parameters in lambda expressions?
  4. In what cases and when can we avoid specifying type for parameters in Lambdas?
  5. 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.
SyntaxMeaningExample
parameter -> expression sasdasdadsadadadadadasSimplest 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() )
() -> expressionLambda that requires no parameters , one still provides an empty parenthesisRunnable 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 ....) -> expressionWhen 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 lambdaThe 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) -> expressionJust like method parameters, you can add annotations to lambda parameters(@NonNull String name) -> ....
(final type parameter) -> expressionSimilarly, one can add final modifier to typed parameter in Lambda expressions(final String name) -> ....



No comments:

Post a Comment