Lambda expressions 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){

    public void testOther(OtherExecutable e){

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() {
            public void execute() {
                System.out.println("Execute code using legacy code");

        //here we are passing the implementation of execute using lambda expression
                    System.out.println("It's lambda expression");


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



You may also like...