Friday, May 3, 2019

Lambda expressions

1. Lambda expressions are just like functions and they accept parameters just like functions.
2. Lambda expression provides implementation of functional interface. An interface which has only one abstract method is called functional interface. Java provides an anotation @FunctionalInterface, which is used to declare an interface as functional interface.

An example is java.lang.Runnable.


//Thread Example without lambda using anonymous class
        Runnable r1=new Runnable(){
            public void run(){
                System.out.println("Thread1 is running...");
            }
        };
        Thread t1=new Thread(r1);
        t1.start();
        //Thread Example with lambda  
        Runnable r2=()->{
                System.out.println("Thread2 is running...");
        };
        Thread t2=new Thread(r2);
        t2.start();

Java Lambda Expression Syntax
(argument-list) -> {body}

Java lambda expression is consisted of three components.

1) Argument-list: It can be empty or non-empty as well.

2) Arrow-token: It is used to link arguments-list and body of expression.

3) Body: It contains expressions and statements for lambda expression.

_____________________________________________________________________

@FunctionalInterface  //It is optional
interface FuncInterface1
{
    // An abstract function
    void abstractFun();

    // A non-abstract (or default) function
    default void normalFun()
    {
       System.out.println("Hello");
    }
}

@FunctionalInterface
interface FuncInterface2
{
    // An abstract function
    void abstractFun(int x);

    // A non-abstract (or default) function
    default void normalFun()
    {
       System.out.println("Hello");
    }
}

interface Addable{
    int add(int a,int b);
}

class Test
{
    public static void main(String args[])
    {
        // lambda expression to implement above
        // functional interface.
        FuncInterface1 fobj1 = ()->{ System.out.println("lamda"); }; //No Parameter

        // This calls above lambda expression.
        fobj1.abstractFun();

 FuncInterface2 fobj2 = (int x)->{ System.out.println("lamda " + 2*x); }; //One Parameter
        fobj2.abstractFun(5);

        Addable ad1=(a,b)->(a+b);  // Multiple parameters
        System.out.println(ad1.add(10,20));
       
        Addable ad2=(int a,int b)->(a+b);  // Multiple parameters with data type
        System.out.println(ad2.add(100,200));

    }
}

No comments:

Post a Comment

Web Development

Design Phase:- Below all these represent different stages of the UX/UI design flow:- Wireframes represent a very basic & visual repr...