Functional programming and Lambda Expressions in Java 8

Introduction

Lambda Expression is concept of functional programming in Java where:

  • You can pass functionality as data or
  • Code as data

As mentioned in an earlier post, this is possible because of JSR-335 and we shall see why Java developers must have insisted on introduction of functional programming in Java, therefore we(Java developers) are not left out among new kids in the blocks like node.js, Scala, R, etc.

1.Functional Programming and the other programming languages

Functional programming is not a new concept. In fact it is dated way back at the time of Perl, Haskell, python, etc. Its easier to be adapted for mathematical operations because everything is considered as an expression in functional programming. Moreover, on contrary there were many criticism about performance issues of functional programming. Benefits of OOP were rated high and people started migrating to it, thanks to enterprise applications and event driven GUI. Lately many benefits of functional programming have been realized to this very own event driven models and people are starting to leverage the benefits (I am not sure about the performance issues yet). Ironically Java, who is best OOP guy around, thought to incorporate some aspects of Functional Programming in its Language. Why? Of course people might have some good reason about it.

Lets see some example codes of other programming languages.

1.1 Scala

Lets see an example in Scala language here:

def func1():Int => Int = {
     def add(x:int, y:int) = x+ y
     add
}

val f = func1()

println(f(10,5))

Hence, let’s see what’s happening here for those who aren’t much familiar with Scala. This is an example of a function closure where func1(), a function which has no argument but returns a reference of function add() which has two int arguments and returns an int type value. (Sounds complicated, but say the above line while reading the code you will get it!). When a call to f(10,5) is made, copy of add is executed and hence summation of 10 and 5.

1.2 JavaScript

This is one of my favorite language. No rules, just timeless magic. Let’s see some function closure with higher order functions in JavaScript.

var forEach = function (arr, task) {
  for (var i = 0; i < arr.length; i++) {
    task(arr[i]);
  }
};

var logIt = function (item) {
  console.log(item);
};

var langs = ["Java", "Scala", "JS", "C", "Ruby"];

forEach(langs , logIt );

In forEach() we have two arguments. langs is an array which will be traversed in forEach() function. The reference of logIt is passed and the reference is assigned to task variable. Task is called (logIt) inside the for loop in the forEach() loop. For a moment it might seem that a nice forEach() construct might be there in JavaScript. But its a magic of callbacks in higher order functional closures.

Python, node.js are leveraging the benefits of this arrangement and are becoming more popular in building web services domain. Reasons are simple:

  1. Reduces a lot of code (depends which language you are using)
  2. Human readability (not always, if you are new to functional programming)
  3. Rapid development (most important, especially for those startup freaks who wants prototype up and running before event the baby is born)

Java community was noticing this, and we all know the power of Java as a language and as JVM. They brought in the concept of Functional Interface to introduce Functional Programming and hence leverage benefits of Functional Programming along with the OOP !!!

2.Do it the Java Style

If you are a Java developer you must have come across the concept of Anonymous inner class. Anonymous inner class is a class with no name implementation of interface or abstract class. Remember this?

interface Vehicle {
  public void runs(int speed);
}
....
// somewhere in some function

    Vehicle vehicle2 = new Vehicle() {
      
      @Override
      public void runs(int speed) {
        System.out.println("Hello world at:"+speed);
        
      }
    };
    verhicle2.runs(20); 

...

Benefits of anonymous inner classes are well known:

  1. Less verbosity ( but at times less readable, no offense but its my opinion)
  2. Reduced code ( ya, that’s my favorite)

You might observed that:

  1. Most of closure like functionality can be useful for places where anonymous inner classes are used.
  2. A common pattern would be an interface with only one abstract method which could be used as callback. This pattern can be used as closure for functional programming. And for this they brought in the concept of Functional Interface.

Functional interface is an interface with only one abstract method. Java developers smartly used the functional interface as a substitute to expression (we are not talking expression!! remember we are discussing functional programming where everything is expression, rather than talking objects) which we call it Lambda Expression.

Let’s see some piece of code to understand how can we use Lambda Expression:

interface Vehicle {
  public void runs(int speed);
}

class Person{
  public void driveVehicle (Vehicle vehicle){
    vehicle.runs(100);
  }
}

class Car implements Vehicle{

  @Override
  public void runs(int speed) {
    System.out.println("Hi I am running at the speed:"+speed);
    
  }
  
}

public class LambdaIntro {
  public static void main(String[] args) {
  
    Vehicle vehicle2 = new Vehicle() {
      
      @Override
      public void runs(int speed) {
        System.out.println("Hello world at:"+speed);
        
      }
    };
    person.driveVehicle(vehicle2);
  
  }
}



Now you can compare this with some basic closure as done in Javascript (Old fashion call back, dont form hard analogy, this is just for understanding purpose):

// javascript code

var run = function (speed) {
     console.log ('running at' +speed );
}

var driveVehicle ( runAt) {
     runAt (20);
}

driveVehicle (run);

3.Lambda Expression

Now let’s write this functional closure as an expression, which of course is called Lambda Expression. The same example in Java we shall write with Lambda Expression (I have not repeated some classes from above Java Snippets):

Vehicle vehicle3 = (int speed)->{System.out.println("Hello at: "+speed);};
person.driveVehicle(vehicle3);

We see that vehicle3 now has assigned an “expression” which is passed in driveVehicle() function. The round bracket has arguments and curly brackets has method body. You can compare this with Scala snippet. Not that I am indicating that syntax is derived, but an example to indicate analogy in the concept. Except for that here we are dealing with interfaces.

The expression is substituted for Vehicle Interface. And observe that the Vehicle Interface has only one abstract method. This matches with the saying of Functional interface as I mentioned above.

Some other examples:

interface SimpleMaths {
  public int arithmatic (int a, int b);

}
...
// somewhere in some function

SimpleMaths addition = ( a, b) -> a + b; 

....
int sum = addition.arithmatic(5, 5);
...

One more:

interface PrintMessage {
  public void print(String message);
}

..
/// somewhere in some function 
PrintMessage printMessage = message ->  {System.out.println(message);};
..
printMessage.print("Hello Lambda"); 

..

There are some important Characteristics of Lambda Expressions. You can find more about this slideshare:

Hope this helps to understanding of Lambda Expressions in Java 8.

Further Reading:

Functional Interfaces in Java 8
Method References in Java 8
Streams in Java 8
Online Video Tutorial for Java 8