Saturday, March 28, 2015

Lambda Expression in Java 8

Let's go functional!

Lambda Expression (Closure or Anonymous method) is one of the most important additions to Java 8.  In fact, it's the most incredible additions to language in its history; it is going to change the way we write programs in Java.  With this new feature, Java adds one of the modern programming technique, Functional Programming.

This is useful for Functional Interfaces (the interface that requires exactly one method to be implemented). Runnable, Callable, Comparable and other interfaces which just have a single method are called functional interfaces. You can even define your own interface with a single method to unleash the power of Lambdas.

Syntax of Lambda

Lambda consists of 3 parts :
  1. Parenthesized set of parameters
  2. Arrow sign ( -> )
  3. Body in form of single expression or a block 
i.e. (Parameter1 p1, Parameter2 p2)            ->                           { }
       (parameters)                                   (arrow sign)          (method body)

  • It doesn't have an explicit name for the method, so it's called an anonymous method as well
  • It can throw Exceptions
  • It's more like a method (and not a class), it has a list of parameter, body and return type
  • It can be passed as an argument to a method and can be stored as a value in a variable

Runnable Implementation without Lambdas

Before going all out on Lambda. Let's see how these interfaces get implemented without it.

Approach 1: Implement the interface

public class MyRunnableImpl implements Runnable{
     public void run(){
         //TODO: Implementation

Approach 2: Using anonymous (inner) class
Runnable task = new Runnable(){
    public void run(){
       //TODO: Implementation

Approach 2 is better than first but still, it's quite verbose and there is hardly any scope of reusability.

Implementing functional interfaces through Lambda

The compiler knows beforehand that the Runnable interface has only one method to be implemented. So this lack of ambiguity around which method needs to be implemented helps in making the Runnable implementation more compact and efficient using lambdas. 

So using Lambda; above code can be replaced as :

Runnable task = () -> System.out.println("inside run method");
Runnable task = () -> { System.out.println("inside run method"); };

And on similar lines you can implement Callable as well :

Callable<Integer> task = () -> {
       Random r = new Random(101);
       return r.nextInt(101);

If the method takes some argument, then they get passed inside parentheses. Let's take case of Comparator interface:

Comparator<String> c = (String a, String b) -> { return a.compareTo(b); };

Before version 8, the lowest level of abstraction in Java was classes. Functions were not treated as the first-class citizen as you need to have an object handle to use functions (functions don't exist without object). But functions are as valuable and important as objects and classes. Programming languages with first-class functions let you find more opportunities for abstraction which means your code is smaller, lighter, more reusable and scalable.

Related Post: Functional Interfaces

keep coding !!!

No comments:

Post a Comment