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 addition 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 (interface that requires exactly one method to be implemented). Runnable, Callable, Comparable and other interfaces which just have a single method are called as 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)

Properties:
  • It doesn't have a explicit name of the method, so it's called as anonymous method as well
  • It can throw Exceptions
  • It's more like a method (and not a class), it has list of parameter, body and return type
  • It can be passed as argument to a method and can be stored as 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{
     @override
     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

Compiler knows before hand 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");
or 
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, lowest level of abstraction in Java was classes. Functions were not treated as 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 you code is smaller, lighter, more reusable and scalable.

Related Post : Functional Interfaces

---
keep coding !!!

No comments:

Post a Comment