Thursday, February 23, 2017

Lambdas in Java(1.8) - 1


Lambdas

reference :https://www.youtube.com/watch?v=gpIUfj3KaOc

They are a concept of passing a method definition itself in a very short form over passing and argument using a method definition.
In other words, A piece of code gets assigned to a method itself (a block of code) .
Something like :

  • aBlockofCode = public void perform(){System.out.print("Hello");}... All Lambda expressions are in orange text below:
However, with the right syntax:
  • Ex 1: aBlockofCode= () -> {System.out.print("Hello");}
  • the bolded expression is a lambda expression.
  • //note that  ";" is within the curly braces
  • The braces is not requires if the block of code contains only one statement.
  • Ex 2: aBlockofCode= (int a) -> a*2;//here, the functions takes a param int a, and returns (a*2). The statement "return" is ignored here, since blocking(using curly braces for multiple statments) is not required. However, if block of code, return needs to be defnied wenevr required.
  • Ex 3: aBlockofCode=  (int a,int b) -> { 
if(b==0) return 0; 
    return a/b;
      };
      • Ex 4: aBlockofCode= (String s) -> s.length();

      While the orange text is referring a lambda expression, a lambda expression can be defined as a interface. Refer the examples below for more understanding:

      public class Lambdas {
      public static void main(String[] args) {
      PrintHalloLambdaInterface halloVarLambda = ()->System.out.println("hello");// --(A)
      halloVarLambda.PrintHalloMethod();
      AddParamsLambdaInterface addParams = (int a, int b)->a+b;// --(B)
      System.out.println(addParams.PrintSum(2, 3));
      StringLengthLambdaInterface strLenLambda =(String s)->s.length();// --(C)
      System.out.println(strLenLambda.PrintStrLength("StringLength"));
      }

      interface PrintHalloLambdaInterface{
       void PrintHalloMethod(); //param not taken or returns- implemented body in//  --(A)
      }
      interface AddParamsLambdaInterface{
       int PrintSum(int a, int b);//2 int params taken and returns an int- implemented body in // --(B)
      }
      interface StringLengthLambdaInterface{
       int PrintStrLength(String str);
      }
      }


      Note:
      • TYPE INFERENCE - Replacing "String s" with just "s" is valid in --(C)
        • StringLengthLambdaInterface strLenLambda = s ->s.length();// --(C)
      • A LambdaInterface can have only one abstract method(Functional Interface) that matches the lambda 



      No comments:

      Post a Comment