Seeing the history of Java we can easily say, Java had troubles adapting functional programming. Recently Oracle has made some efforts to bring functional programming pattern to Java. In this blog we are going to discuss about Java  lambda and functional programming.

What is functional programming?

Functional programming focused mainly on three points while function creation pure functions, avoid sharing state and immutable variables.
In Java world methods were part of the class and they used to use instance state (object properties) and modify them. But pure function concept says method return should solely be based on method argument and it shouldn’t share state. Immutable variables are never changed in whole function call they create a copy of the value, such as primitive types. Perks of functional programming function can be passed as an argument and returned same as the objects. For example

class Utility{
   private int i=5;

   //Pure function, It does not use instance variables
   public int sumToInt(int a, int b){
       return a+b;
   }

   //Not a pure function
   public int sumWithInstance(int a){
       return a+i;
   }
}

How Java has added functional programming

To support functional programming Java had to support methods without a class. As you might be aware to create a method in Java we always needed a class but functional programming requires the function to be independent of class.

class Utilty{
    public int addInt(int a, int b){
        return a+b;
    }
}

Utilty utilty = new Utilty();
utilty.addInt(1, 3);

Here just to add two integers we had to create a class and to access methods you need to create class object and access. But as you can see this function is a pure function, it doesn’t use object state and return the values based on input variables. For this Java 8 introduced function interfaces.

Java 8 lambda and functional programming

interface AddInt{  //Line1
    int addInt(int a, int b);
}

AddInt addFunc = (a,b) -> { return a+b; } //Line 2
//or
AddInt addFunc = (a,b) -> a+b; //Line 2

System.out.println(addFunc.addInt(1,2)); // prints 3

Let’s forget about the interface, what just happened with line 2. You must have seen in Javascript something like this.

//Javascript
var addFunc = function(a,b){
    return a+b;
}
//or
var addFunc = (a,b) => {return a+b;}
//or since the functions body is one liner
var addFunc = (a,b) => a+b;

console.log(addFunc(1,2)) // prints 3

In javascript, we save function definition in a variable and call it later same even Java 8 provides the way to achieve it. The only issue remains Java doesn’t have a ‘var’ keyword so it usage interface/abstract class with only 1 abstract method. The whole interface/class is created only for that function. This was a quick introduction on the functional interface and harness full power of these interfaces we have lambda way coding.  Please check part 2 of this blog.