Lambda expression in Java

Lambda expressions were introduced in Java 8. They are also called as anonymous methods. Below example explains how we can use Lambda expressions.
 
package lambda;

/**
 * Created by ssalunke on 14/04/2016.
 */

interface Executable{
    public void execute();
}

interface OtherExecutable{
    public void executeOther(int a);
}

class X {
    //all that test method needs is block of code
    //as per the interface Executable
    public void test(Executable e){
        e.execute();
    }

    public void testOther(OtherExecutable e){
        e.executeOther(10);
    }
}

public class Lambda {

    public static void main(String [] args){
        X x1 = new X();

        //here we are passing the implementation of execute method
        x1.test(new Executable() {
            @Override
            public void execute() {
                System.out.println("Execute code using legacy code");
            }
        });

        //here we are passing the implementation of execute using lambda expression
        x1.test(()->
                {
                    System.out.println("hi");
                    System.out.println("It's lambda expression");
                }

        );

        x1.testOther((a) -> System.out.println("This lambda takes in 1 int parameter a -> " + a) );

    }

}


Web development and Automation testing

solutions delivered!!