Lambda Expression In Java

Lambda expression is similar to java method, but lambda expression does not need name and it can be implemented in the body of a method. It is an instance of functional interface. An interface with a single abstract method is called functional interface.
The lambda expression is a short block of code which takes parameters and returns a value

  1. Lambda expression is similar to java method but without name.
  2. Lambda expression can be created without belonging to any class, it can be implemented in the body of a method.
  3. Lambda expression is an instance of functional interface.
  4. Lambda expression is a short block of code which takes parameters and returns a value.

Syntax:

parameter -> expression
//Syntax of more than one parameters
(parameter1, parameter2) -> expression

- Example of lambda expression


/*@FunctionalInterface*/   //It is optional
public interface MultipleInterface {
    public int multiple(int x,int y);
}

public class Calculate{
  public static void main (String[] args) { 
    //with lambda
        MultipleInterface m = (x, y) -> {
        return x * y;
      }

    int multipleVal =   m.multiple(10,30);
    System.out.println( "Multiple Value is "+multipleVal);
}

Output:
    Multiple Value is 300


Example of lambda expression with forEach() method.

//Importing required classes
import java.util.*; 
import java.io.*; 
import java.util.stream.*; 

public class LambdaExample {

public static void main (String args[]){  
  
  Integer[] numbers = { 100, 20, 13, 440, 5, 16, 7, 28, 2, 11, 1 };
  
  Arrays.asList(numbers)
        .forEach((i) -> { System.out.println(); } );
                 
 }
}

Output:
    100
    20
    13
    440
    5
    16
    7
    28
    2
    11
    1

Example of lambda expression with consumer.

//Importing required classes
import java.util.*; 
import java.io.*; 
import java.util.stream.*; 

public class LambdaExample {

public static void main (String args[]){  
    Integer[] numbers = {100,20,13,440,5,16,7,28,2,11,1};
    Consumer consumerMethod = (i) -> { System.out.println(i); };
    Arrays.asList(numbers)
        .forEach( consumerMethod );
                 
 }
}

Output:
    100
    20
    13
    440
    5
    16
    7
    28
    2
    11
    1