Lambda Expression in Java

"Lambda Expressions in Java are the short block of code that accepts input as parameters and returns a resultant value". 

It is same as lambda functions.

In java, it is normally used to create the instances of functional interfaces (A functional interface is an interface with a single abstract method).

Lambda Expressions are recently introduced in Java SE 8. 

Functionalities of Lambda Expression : -

  • Lambda Expressions implement the only abstract function and therefore implement functional interfaces.
  • It enables to treat functionality as a method argument, or code as data.
  • With help of Lambda expression, a function that can be created without belonging to any class.
  • A lambda expression can be passed around as if it was an object and executed on demand.

Lambda Expression Syntax:- 

A lambda expression is written by the following syntax.

parameter -> expression body

Lambda Expression Parameters:- 

There are three types of Lambda Expression Parameters are mentioned below:

  1. Zero Parameter
  2. Single Parameter
  3. Multiple Parameters

1. Lambda Expression with Zero parameter 

() -> System.out.println("Zero parameter lambda");

Example:

public class Java8LambdaTester {
interface HelloService {
      void sayHello();
}
public static void main(String args[]) {
    HelloService svc1 = ()-> System.out.println("Hello. This is Zero parameter lambda");
svc1.sayHello();
}
}

output: Hello. This is Zero parameter lambda

2. Lambda Expression with Single parameter

(p) -> System.out.println("One parameter: " + p);

Example 1:

public class Java8LambdaTester {
interface HelloService {
      void sayHelloWithName(String message);
}
public static void main(String args[]) {
    HelloService svc1 = (String message)-> System.out.println("Hello "+ message +"!!. This is one parameter lambda");
svc1.sayHelloWithName("Ramesh");
}
}

output: Hello Ramesh!!. This is one parameter lambda

It is not mandatory to use parentheses in lambda parameters, if the type of that variable can be inferred from the context.

Example 2:

// A Java program to demonstrate simple lambda expressions

import java.util.ArrayList;
class LambdaTest {
    public static void main(String args[])
    {
        // Creating an ArrayList with elements
        // {1, 2, 3, 4}
        ArrayList<Integer> arrL = new ArrayList<Integer>();
        arrL.add(1);
        arrL.add(2);
        arrL.add(3);
        arrL.add(4);
 
        // Using lambda expression to print all elements
        // of arrL
        arrL.forEach(n -> System.out.println(n));
 
        // Using lambda expression to print even elements
        // of arrL
        arrL.forEach(n -> {
            if (n % 2 == 0)
                System.out.println(n);
        });
    }
}
Output:
1
2
3
4
2
4

3. Lambda Expression with Multiple parameters

(p1, p2) -> System.out.println("Multiple parameters: " + p1 + ", " + p2);

A Java program to demonstrate the working of a lambda expression with two arguments. 

  1. public class LambdaTest {
  2.     // operation will be implemented using lambda expressions
  3.     interface MathOperation  {
  4.         int operation(int a, int b);
  5.     }
  6.  
  7.     // sayMessage() will implemented using lambda expressions
  8.     interface GreetingService {
  9.         void sayMessage(String message);
  10.     }
  11.  
  12.     // Performs MathOperation's operation on 'a' and 'b'
  13.     private int operate(int a, int b, MathOperation fobj)
  14.     {
  15.         return fobj.operation(a, b);
  16.     }
  17.  
  18.     public static void main(String args[])
  19.     {
  20.   /* lambda expression for addition for two parameters data type for x            and y is optional. This expression implements 'MathOperation'         interface */ 
  21.         MathOperation add = (int x, int y) -> x + y;
  22.  
  23.         // lambda expression multiplication for two
  24.         // parameters This expression also implements
  25.         // 'MathOperation' interface
  26.         MathOperation multiply = (int x, int y) -> {
  27.         System.out.println("hello ");
  28.          return x * y;
  29.         };
  30.  
  31.         // Creating an object of LambdaTest to call operate     //using different implementations using lambda Expressions
  32.         LambdaTest tobj = new LambdaTest();
  33.  
  34.         // Add two numbers using lambda expression
  35.         System.out.println("Addition is "
  36.                            + tobj.operate(6, 3, add));
  37.  
  38.         // Multiply two numbers using lambda expression
  39.         System.out.println("Multiplication is "
  40.                            + tobj.operate(6, 3, multiply));
  41.  
  42.         // lambda expression for single parameter
  43.         // This expression implements 'GreetingService' interface
  44.         GreetingService fobj = message -> System.out.println("Hello " + message);
  45.         fobj.sayMessage("JavaHubPoint");
  46.     }
  47. }

Output: 

Addition is 9
hello
Multiplication is 18
Hello JavaHubPoint


Conclusion:-

Following are the important Conclusions from a lambda expression.

  1. Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter. See line number 41. 
  2. Optional parenthesis around parameter − No need to declare parenthesis for a single parameter. For multiple parameters, parentheses are required. See line number 41.
  3. Optional curly braces − No need to use curly braces in expression body, if the body contains a single statement. See line number 21. The body of a lambda expression can contain zero, one, or more statements. See line number 26.
  4. Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. See line number 21.