Tuesday, June 2, 2015

Lambda Java 8 - Basic and concise introduction

Introduction

Lambda is a new feature added in Java 8. It is an elegant replacement for anonymous classes which implement functional interfaces (interfaces with single method).

For instance, runnable interface has a single method, run().

With anonymous class, a simple implementation, would look like this,
Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        // Your complex logic goes here ..
        System.out.println("Hello World !!");
    }
});
thread.run();

With Lambda, it would look like the below,
Thread thread = new Thread(() -> {
    // Your complex logic goes here ..
    System.out.println("Hello World !!");
});
thread.run();
Can you see the reduced code and increased code clarity. Lambda improves readability. And for understanding performance of lambda, you can read this,
http://wiki.jvmlangsummit.com/images/7/7b/Goetz-jvmls-lambda.pdf

You may wonder, why do we need a concept which just simplifies anonymous classes with single method. For that we need to understand what is the need for single method interface. Generally single method or functional interface is used where the functionality or implementation to be passed as a method argument. In runnable interface, we pass the code to be run by a new thread. In Java core framework, there are a lot of functional interfaces, like Callable, Comparator, etc. If you carefully at those, implementations of these interfaces, are just to pass the code to other methods.

Syntax of Lambda Expression

Comma separated list of parameters, with enclosing paranthesis and parameters don't need data types as it can be inferred; Followed by single arrow, ->

Body with an expression or a block of statements. In case of expression, runtime would evaluate and return the result. in case of statement block, block has to be properly enclosed by curly braces and return statement has to be added, if needed.

For instance, if x and y are parameters to be passed, a simple lambda expression, might look like this,
(x, y) -> {
// Add needed code here.
return x + y;
}

Capturing variable in the enclosed scope

Lambda expressions can capture variables in the enclosing scope without any problems associated with scoping or shadowing. Variables can't be defined in the lambda body scope with a name, if the same variable name has already been used in the enclosing scope. In the following code snippet, lambda uses the variable, name defined in the enclosing scope,
String name = "Karthik";
Thread thread = new Thread(() -> {
    // Your complex logic goes here ..
    System.out.println("Hello " + name + " !!");
});
thread.run();
Hope this post gave some basic ideas on Lambda,

For more information, please refer,

https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

No comments:

Post a Comment