Thursday, July 8, 2021

Lambda Expression

 

 

 

 
Lambda expression is a new and important feature of Java which was included in Java SE 8. It provides a clear and concise way to represent one method interface using an expression.

 

A lambda expression is characterized by the following syntax.

(parameters) -> expression

 Java 8 Functional Interfaces and Lambda Expressions help us in writing smaller and cleaner code by removing a lot of boiler-plate code.

 

In general programming language, a Lambda expression (or function) is an anonymous function, i.e., a function with no name and any identifier.

 

The most important feature of Lambda Expressions is that they execute in the context of their appearance. So, a similar lambda expression can be executed differently in some other context (i.e. logic will be the same but results will be different based on different parameters passed to function).

 

Example: 

 

For example, the given lambda expression takes two parameters and returns their addition.

Based on the type of a and b, the expression will be used differently. If the parameters match to Integer the expression will add the two numbers. If the parameters of type String the expression will concat the two strings.

 

 (a, b) -> a + b    

 

One more Exmple of Lambda Expressions:

 
interface IntegerOperation {

    public String addTwoInteger(Integer a, Integer b);
} 
 
public class Example {

   public static void main(String args[]) {
        // lambda expression with multiple arguments
    	Integer s = (a, b) -> a + b;
        System.out.println("Result: " + s);
    }
}

 

 

 Important Points to be noted:

1. When there is a single parameter, if its type is inferred, it is not mandatory to use parentheses. 

 a -> return a*a.


2. If there are more than 1 statments in the body then they should be enclosed in the braces like below.


(parameters) -> { statements; }





No comments:

Post a Comment