Lambda Expressions

Overview

Lambda expression is used to implement the method body of functional interface directly inside another method or can be assigned to a variable of type functional interface.

Lambda expression was introduced in Java 8. It doesn't have a name but has a list of parameters, a body, a return type and can have a list of exceptions that can be thrown.

Syntax of lambda expression:

Function<Integer,Integer> p = (a)-> a*a;
System.out.println(p.apply(10));
Output:
100

 

In the above code Function is a functional interface(An interface with a single abstract method is called a functional interface. An example is java.lang.Runnable) having one single method apply. and  (a) -> a*a;  is the implementation of the apply method using a lambda expression.

To understand this let's do some coding using Java 7. 

package com.geekscoder.java;

public class MyThread{

    public static void main(String[] args) {
        new Thread(new Runnable() {
           @Override
           public void run() {
               System.out.println("Hello Java");
           }
       }).start();
    }

}

The above code can be replaced using a lambda expression.

package com.geekscoder.java8;

public class MyThread{
    public static void main(String[] args) {
     new Thread(()-> System.out.println("Hello Java")).start();
 }
}

Some examples of valid and Invalid syntax of lambda expression:

1. () -> {}   //valid
2. () -> "Lambda" //valid
3. () -> {return "Java";}  //valid
4. (Integer i) -> return "Java" + i;  // invalid
5. (String s) -> {"Hello Java";} //invalid
  1. This lambda has no parameters and returns void. It’s similar to a method with an empty body i.e public void run() { }.
  2. This lambda has no parameters and returns a String as an expression.
  3. This lambda has no parameters and returns a String (using an explicit return statement).
  4. return is a control-flow statement. To make this lambda valid, curly braces are required as follows: (Integer i) -> {return "Java" + i;}.
  5. “Hello Java” is an expression, not a statement. To make this lambda valid, you can remove the curly braces and semicolon as follows: (String s) -> "Hello Java". Or if you prefer, you can use an explicit return statement as follows: (String s) -> {return "Hello Java";}.

Conclusion:

Lamda is very powerful to express the behavior of a function, we can change the behavior of a functional interface method without implementing it through a class.

Lambda expression can be used in place of an anonymous class with having one method, If an interface has more than one method to implement, in that case, lambda expression can not be used.