refermycode.com

Develop your world..

Lambda Expression in Java

Lambda Expression is way to passing a block of code to a method. To understand this concept we need to implement the functional interface and anonymous class which was used in the earlier version of the Java.

“Lambda Expression term is come from Mathematics, Greek letter Lambda basically associated with some kind of analogous situation where we are passing one function as a parameter to another function.”

package lambdaexpession;
interface Executable {
  void execute();
}

class Runner {
  public void run(Executable e) {
    System.out.println("Executing Code Block…");
    e.execute();
  }
}

public class App {
  public static void main(String args[]) {
    Runner runner = new Runner();
    runner.run(new Executable() {
      public void execute() {
        System.out.println("Anonymous Class Code Block.");
      }
    });
  }
}

The output of above code is

Executing Code Block…
Anonymous Class Code Block.

same thing we can implement with the help of Lambda Expression in following manner,
we need to replace above mentioned anonymous class code block

runner.run(new Executable() {
  public void execute() {
    System.out.println("Anonymous Class Code Block.");
  }
});

with following Lambda Expression,

runner.run( () -> System.out.println("Lambda Expression Code Block. "));

we get same output from Lambda Expression, i.e.

Executing Code Block…
Lambda Expression Code Block.

Hence by using Lambda Expression in Java, we are reducing code complexity and increasing the readability of our application.
Hope, you will get basic idea of Lambda Expression by above mentioned example. Below are some important points which will help you to clear understanding of Lambda Expressions in Java 8.

A) We can replace the Anonymous class with our Lambda Expression.
The below mentioned method

runner.run( () -> System.out.println("Lambda Expression Code Block."));

is replaced the whole anonymous class which is mentioned in above example. i.e.

runner.run(new Executable (){
  public void execute(){
    System.out.println("Anonymous Class Code Block.");
  }
});

where,

runner.run( () -> System.out. ("Lambda Expression Code Block."));

method name which is declared in Runner class.
List of Parameters required for Lambda Expression.
Code block which to be executed.

B) If we want to execute a multiple statements with the Lambda Expression then include the { and } parenthesis to code which you need to be executed. If you are adding multiple statements then it is mandatory to terminate the each statement with the “;”. If you are using { and } parenthesis and you have added single statement only then that single statement is also needs to be terminated with the help of “;”.

runner.run( () -> {
  System.out.println("Lambda Expression Code Block.");
  System.out.println("This is another Statement");
});
  • So, Lambda Expression of rows are associated with interface having single method in it.
  • With the help of Lambda Expression, we are simplifying the syntax for passing actual code to the another method/function.
  • In Java 8, if interface consist of single method in it, then it will refer as functional interface. hence “Interface having single method is called as Functional Interface”.
    exa. Comparable and Runnable interface.
  • C) If we want return value from block of code that is going to be execute,

    package lambdaexpession;

    interface Executable{
      int execute();
    }

    class Runner{
      public void run(Executable e){
        System.out.println("Executing Code Block…");
        int value = e.execute();
        System.out.println("Return value is : "+value);
      }
    }

    public class App{
      public static void main(String args[]){
        Runner runner = new Runner();
        runner.run(new Executable (){
          public int execute(){
            System.out.println("Anonymous Class Code Block.");
            return 7;
          }
        });
      }
    }

    output of above example is,

    Executing Code Block…
    Anonymous Class Code Block.
    Return value is : 7

    same thing we can implement with the help of Lambda Expression in following manner,

    runner.run( () -> {
      System.out.println("Lambda Expression Code Block.");
      return 8;
    });

    Hence, if we replace the above code in our example then we get following output after execution of program,

    Executing Code Block…
    Lambda Expression Code Block.
    Return value is : 8

    D) If we are returning only literal value from Lambda Expression then no need to mentioned the datatype of return value.

    runner.run( () -> 8 );

    E) If we want to pass parameter,

    package lambdaexpession;

    interface Executable {
      int execute(int a);
    }

    class Runner {
      public void run(Executable e) {
        System.out.println("Executing Code Block…");
        int value = e.execute(12);
        System.out.println("Return value is : " + value);
      }
    }

    public class App {
      public static void main(String args[]) {
        Runner runner = new Runner();
        runner.run(new Executable() {
          public int execute(int a) {
            System.out.println("Anonymous Class Code Block.");
            return 7 + a;
          }
        });
      }
    }

    For above mentioned program, we get following output,

    Executing Code Block…
    Anonymous Class Code Block.
    Return value is : 19

    same thing we can implement with the help of Lambda Expression in following manner,

    runner.run( (int a) -> {
      System.out.println("Lambda Expression Code Block.");
      return 7+a;
    });

    we will get following output if we replace anonymous class with our Lambda Expression,

    Executing Code Block…
    Lambda Expression Code Block.
    Return value is : 19

    F) If we are using Lambda Expression then there is no need to define parameter type. Our Compiler will autodetect the type of parameter from the declaration of method from calling class.

    runner.run( (a) -> {
      System.out.println("Lambda Expression Code Block.");
      return 7+a;
    });

    G) In case of method overloading, we need to specify the datatype of parameters to avoid the ambiguity between overloading methods.

    package lambdaexpession;

    interface Executable{
      int execute(int a);
    }

    interface StringExecutable{
      int execute(String a);
    }

    class Runner{
      public void run(Executable e){
        System.out.println("Executing Code Block…");
        int value = e.execute(12);
        System.out.println("Return value is : "+value);
      }
     
      public void run(StringExecutable e){
        System.out.println("Executing Code Block…");
        int value = e.execute("Hello");
        System.out.println("Return value is : "+value);
      }
    }

    public class App{
      public static void main(String args[]){
        Runner runner = new Runner();
        runner.run(new Executable (){
          public int execute(int a){
            System.out.println("Anonymous Class Code Block.");
            return 7 + a;
          }
        });
      }
    }

    so after execution of this code, we will get following output,

    Executing Code Block…
    Anonymous Class Code Block.
    Return value is : 19

    same thing we can implement with the help of Lambda Expression in following manner,

    runner.run( (int a) -> {
      System.out.println("Lambda Expression Code Block.");
      return 7+a;
    });

    so after replacing and executing of our Lambda Expression, we will get following output,

    Executing Code Block…
    Lambda Expression Code Block.
    Return value is : 19

    H) If we have single parameter then no need to define the datatype of parameter as well as no need to add parenthesis for parameters.

    runner.run( a -> {
      System.out.println("Lambda Expression Code Block.");
      return 7+a;
    });

    I) If we want to pass multiple parameters then we need to add parenthesis compulsory.

    runner.run( (a,b) -> {
      System.out.println("Lambda Expression Code Block.");
      return a+b;
    });

    J) If we want to access the variable from main (parent) method in the block of Lambda Expression.

  • If we want to access variable from calling method in the anonymous class then it should be final for previous version of Java. But in Java 8, it is not mandatory to declare that variable as final.
  • But if we are re-assigning the value of that variable then compiler will throw Compile time Exception.
  • Means if we are not re-assigning value to variable in calling method then it is treated like final variable but it is not actually final variable, we can called it as effectively final variable.
  • public class App{
      public static void main(String args[]){
        int c = 100;
        // c=8; mustn’t do this.
        Runner runner = new Runner();
        runner.run(new Executable (){
          public int execute(int a, int b){
            System.out.println("Anonymous Class Code Block.");
            return a+b+c;
          }
        });
      }
    }

    same thing we can implement with the help of Lambda Expression in following manner,

    runner.run( ( a,b ) -> {
      System.out.println("Lambda Expression Code Block.");
      return a+b+c;
    });

    K) Lambda Expression doesn’t have their own scope, so we can access variable from calling method, while in previous version of Java, anonymous class having their own scopes, so you can re-declare the variable with same declaration as declared in the parent method.
    This variable in the anonymous class is treated as new variable.

    public class App{
      public static void main(String args[]){
        int d = 77;
        Runner runner = new Runner();
        runner.run(new Executable (){
          public int execute(int a, int b){
            System.out.println("Lambda Expression Code Block.");
            //int d=8; can do this in anonymous classes.
            return a+b+c;
          }
        });
      }
    }

    same thing we can implement with the help of Lambda Expression in following manner,

    runner.run( ( a,b ) -> {
      System.out.println("Lambda Expression Code Block.");
      //int d=5; we can’t do this as this is no new scope.
      return a+b+c;
    });

    L) We can store all the Lambda Expression into equivalent object also.

    Executable ex = (a,b) -> {
      System.out.println("Lambda Expression Code Block.");
      return a+b;
    }
    runner.run(ex);

    M) We can assign the Lambda Expression to superclass of interface, for that we need to typecast that object to superclass object type.

    Object codeBlock = (Executable) (a,b) -> {
      System.out.println("Lambda Expression Code Block.");
      return a+b;
    }

    This is very useful to implement comparable interface.

    So this is some basic and simple Lambda Expressions which is used in Java 8. We will see some real time examples of Lambda Expressions in our Next Post.

    Hope this blog will help you to understand the basic concept of Lambda Expressions in Java 8.
    Please don’t forget to comment your feedback for this post. 🙂

    References : Video of Cave of Programming.