Saturday, 14 November 2020

Java 8 – Lambda Expression


Lambda Expression in Java 1.8 version

It is introduced in Java ecosystem to bring benefits of Functional programming concepts. Let us look at attributes about it,

  • It is an anonymous function or nameless i.e.; a method without name
  • Return type is not required, as it could be inferred during course of program execution
  • Absolutely not required to mention access-modifiers, as it will be local to where it is declared/defined. But declaring doesn’t result into any error.

So what is actually required to identify a Lambda expression,

  • arguments lists, if any otherwise empty parenthesis ( )
  • execution part or logic or body or set of correct java statement

Lambda expression syntax

(argument list)->{function_body};

Where,

  • argument lists is number of input arguments or parameter
  • function body (method implementation) is set of Java statement within curly braces
  • And there is special symbol for Lambda expression that is hyphen followed by greater than sign i.e.; ->
    Example – (argument_list) -> {method_body};
  • There are certain rules regarding above syntax (->) which we will discuss at the end of this topic


Lambda Expression consists following things only,

  • input arguments list inside parenthesis
  • method body within curly braces

@FunctionalInterface
interface DemoInterface {
    public void display();
}
 
public class TestLambdaExpression {
 
    // main method
    public static void main(String[] args) {
 
        // Lambda Expression equivalent for above method
        DemoInterface d = () -> System.out.println("Hello World");
 
        // how to invoke Lambda Expression -> Functional Interface
        d.display();
    }
}

No comments:

Post a Comment