What is lambda expression in java

Lambda Expression:-

Lambda expression is new feature introduced in java 8.Lambda expression is anonymous function in java.In other words lambda express don’t have name and does not belong to any class. Its simple block of code.

  • Lambda expression provides implementation of functional interface.
  • Lambda expression have zero, one or more parameters.
  • Lambda expression body contains zero or more expression.
  • Java compiler resolve type of lambda parameter with the help of type inference so adding type of parameter is option and can be excluded.
  • Lambda expression require parenthesis only if there is more than one parameter or when there is no parameter.
  • In Lambda expression if there is only one statement you may or may not use return statement.

You can use lambda expression instead of anonymous inner class.

Advantages of Lambda Expression:-

We used less code with Lambda expression.

You can use Lambda expression with your old code.

Syntax:-

In Lambda expression on left hand side of lambda operator we need to specify parameters and right hand side need to specify expression.

 

Syntax:-

(parameter_list)->{ body}

Lets see some example of Lambda Expression.

Lambda Expression with No Parameter:-

 

Example:-

package com.javatechexpert;

@FunctionalInterface

interface MyInterface{

public String display();

}
public class Lambdaexpression {

public static void main(String[] args) {

//with lambda

MyInterface i1=()->{

return "Javatech Expert";

};

System.out.println(i1.display());

}

}

 

Output :- Javatech Expert

 

 

Lambda Expression with Single Parameter:-

 

Example:-

package com.javatechexpert;

@FunctionalInterface

interface MyInterface{

public int addition(int a);

}

public class Lambdaexpression {

public static void main(String[] args) {

// lambda with single parameter

MyInterface i1=(num) -> num+5;

System.out.println(i1.addition(50));

}

}

 

Output:- 55

 

Lambda Expression  with Multiple Parameter:-

Example:-

package com.javatechexpert;

@FunctionalInterface

interface MyInterface{

public int addition(int a,int b);

}

public class Lambdaexpression {


public static void main(String[] args) {

// lambda with single parameter

MyInterface i1=(a,b) -> a+b;

System.out.println(i1.addition(50,20));

}

}

 

Output:-70
Reference:-

Lambda Expression

Java 8 interview Questions and Answers

 

Leave a Reply

%d bloggers like this: