Friday, 26 August 2016

Java8 - Lambda Expressions

Lambda Expressions are Java8 new features. Lambda expressions are mainly used to implemented functional interfaces. We will try to understand
need and use of Lambda Expressions in this blog.

Why Lambda Expression -
We know that Java is an object oriented programming language, If we leave primitive variables than everything else in java is object based. 
But sometime we need to pass a function in a method. In functional programming we have a special feature called closure (closure is a function that can be stored as a variable - referred to as a "first-class function"), but in Java there is nothing like closure. To do the same in Java we use Anonymous class.
The problem with Anonymous classes are the complex syntax. For simple operation also we need to write additional syntactical code each time. The problem of bulky syntax is refereed as “Vertical problem” by Java people. So to bridge this gap between functional and OOP's programming Java introduced Lambda expressions, which are simply alternate of anonymous classes but only for the interfaces with single abstract methods (Functional Interfaces), in case of non functional interfaces we still need to use the anonymous class.

For example : consider the EventListener interface
button.addEventListener(new EventListener() {
   public void onEvent(Event e) {
      // code goes here .....
   }
});

For example - If we use anonymous class and we want to add above event code with more than one button, than we need to write the full code for each button(basically to avoid writing an implementation class for interface). Lambda Expressions also resolve this issue.

What is a Lambda Expression ?
In very simple words Lambda Expressions represent an anonymous function. Which can be passed as a parameter like an object and can be executed when required.

Type of a Lambda Expression will be of a some functional interface. We can store the Lambda Expression in a functional interface type and can execute it when required. This is basically solution of bulky anonymous implementation multiple times in a class.

Lambda Expressions introduced with a specific syntax. Basic syntax is -
(Argument List) -> (Function Body)

(int arg1, int arg2) -> {System.out.println("Passed arguments are - Frist: "+arg1+" Second: "+arg2)}

Let's understand all part of a Lambda Expression in detail.

Argument List

  • A lambda expression can have zero or more comma separated arguments in argument list.
  • Arguments in Lambda Expression can be passed with or without type, but you can not mix both together. Below given both are equal and valid Lambda expressions.
    (int arg1, int arg2) -> {System.out.println("Passed arguments
    are - Frist: "+arg1+" Second: "+arg2)}

    (arg1, arg2) -> {System.out.println("Passed arguments are - 
    Frist: "+arg1+" Second: "+arg2)}
  • "()" can be removed if there is only one argument in Lambda Expression.
    arg1 -> {System.out.println("Passed argument is : "+arg1)}

Function Body -
  • In Lambda Expression body there can be single or multiple statements.
  • If body contains only single statement, than it will be executed and result will be returned automatically.
         () -> {System.out.println("Nothing to print ...")}
  • If multiple statements are there in function body, it will execute all and add a return statement automatically on the basis of Functional Interface method return type. Or we can write return statement manually. 
         () -> {System.out.println("Nothing to print ...");
           System.out.println("Just to make multiline ...");}
  • If return statement is not written as last statement manually, java will try to put a return statement. So don't put any branching statement as last statement.  Below is a invalid lambda expression.
         () -> {System.out.println("Nothing to print ...");
           break;} //compile time error.

Now we can take a look of different valid Lambda expressions -

  1. () -> {System.out.println("Nothing to print ...")}
  2. arg1 -> {System.out.println("Passed argument is : "+arg1)}
  3. (arg1) -> {System.out.println("Passed argument is : "+arg1)}
  4. (String arg1) -> {System.out.println("Passed argument is : "+arg1)}
  5. (arg1, arg2) -> {System.out.println("Passed arguments
        are - Frist: "+arg1+" Second: "+arg2)}
  6. (int arg1, int arg2) -> {System.out.println("Passed arguments
        are - Frist: "+arg1+" Second: "+arg2)}
  7. () -> {System.out.println("Nothing to print ...");
               System.out.println("Just to make multiline ...");}
  8. () -> {System.out.println("Nothing to print ...");
               return "return is allowed";}
That's all about basics of Lambda Expressions, I hope now you have a good idea about Java8 Lambda Expressions. I will try to explain more new feature in my upcoming post. 

2 comments:

  1. Nice blog very precise and to the point. Abt what type of things can be applicable on lambda topic can be elaborate more with types of functional interfaces like supplier or consumer etc. -Lokesh

    ReplyDelete
  2. Thanks Lokesh. I will definitely work on your suggestions.

    ReplyDelete