Part 1 – Lambda Expressions Java 8

Lambda Expressions Java 8

What is Lambda Expression in Java 8?

Lambda expression facilitates the functional programming and simplifies the development. Lambda expression is a shorter way of writing an implementation of a single abstract method interface. Lambda expressions are used to create anonymous functions. Syntax: (parameters) -> expression or (parameters) -> { statements; } Java 8 provide support for lambda expressions only with functional interfaces. Lets see how to use lambda to remove the boilerplate code. We will implement the Runnable interface with anonymous class and with lambda expression.

private static void simpleConceptWithRunnable() {
 Runnable runnable = new Runnable() { // boilerplate code which needs to be written everytime
  @Override
  public void run() {
   System.out.println("Inside annonymos inner class");
  }
 };
 
 Runnable runnable2 = () -> { // Lambda expression
         System.out.println("Inside lambda expression");
    };
 
 Thread thread = new Thread(runnable);
 thread.start();
 
 thread = new Thread(runnable2);
 thread.start();
}

We wrote a boilerplate code of creating an anonymous class and override the run method. Lambda takes care of this things and gives us a simple syntax to create a anonymous class. Lambdas are more than anonymous classes.

Lambda Expression with Parameters

1. No Parameters –

Runnable runnable2 = () -> System.out.println("Inside lambda expression");


2.Single Parameter –

interface SingleParam {

public void print(String param);

}

SingleParam singleParam = (param) -> {System.out.printf("Hello %s",param);};

singleParam.print("saurabh");


3. Multiple parameters –

interface MultipleParam {

public void print(String param1, String param2);

}

MultipleParam multipleParam = (param1, param2) ->
                    System.out.printf("param1 : %s, param2: %sn", param1, param2);

multipleParams.print("OnlyFullstack", "Development");

Let’s go to our next tutorial where we will discuss below points :

 – The difference in between Lambda Expression and Anonymous class 
PART 2 – LAMBDA VS ANONYMOUS CLASS IN JAVA 8