Lambda and Functional Interfaces

First Cute Lambda and Introduction to Functional Interfaces

April 5, 2020

In this part of the tutorial, we will Introduce Lambda and Functional Interfaces. These two things should always be discussed together as lambda can’t exist without Functional Interfaces.

Lambda is the most discussed topic in Java after Java 8 launch. Lambda is basically a building block of Functional Programming
Lambda is a function without a Name and this is also called a anonymous function.
Let me try to take you through since the Beginnning and we will evolve Lambda

So,Lambda got Introduced in Java 8, What about before that?
Let’s take an example.

To create a thread in Java : One can either implement Runnable Interafces or Extend the Thread class. Right?
Let’s create a Thread by implementing a Runnable interface

class MyThread implements Runnable{

@Override
public void run(){

System.out.println("Thread t1 Executed"); 
// Let's not do much here, .lets only say ... Thread Executed

}}

public class LambdaExample01{

public static void main(String[] args) {

Thread t1=new Thread(new MyThread());   
System.out.println("Main Thread");
t1.start();
   

Let’s simplify this a little
Before Java 8 If we want to supply a method implementation on the Fly
We could use the Anonymous classes
Let’s Use Anonymous class rather an outer class

// This is Anonymous Class without any name

Thread t2 = new Thread( new Runnable() {
@Override

// We got rid of name and the code became a little consise

public void run() {
System.out.println(“In thread t2”);
}
}
);
t2.start();

so, this is the way but is this the most concise way ?
Before Java 8, Possibaly.

But after Java 8, we have Lambda.
Let’s try to reduce this further to make it more Concise
A function has 4 properties

  • Name of the Function
  • Parameters list
  • Body of the Function
  • Return Type

Let’s see how we can play with that in Java 8 and beyond

Thread t3 = new Thread( new Runnable() {

// We can actually remove this Outer class because this is an unnecessary //noise and Java 8 Compiler can anyway detect that,

//This Interface is having only
// One Method Run
@Override
public void run() {

We can remove name, return type and access modifier of the Method becaue this Runnable is

having only one Method run so Compiler can guess these things using its declaration present in the interface.


System.out.println(“In thread t3”);

let’s remove access modifier because the methods should anyways be public in the interface if someone is accessing it outside
}

Remove the return type because compiler can guess the return type beyond Java 8 based on the Context using type inference


So what is left – the most important part of the function, which is the function body.

By putting this little Arrow between the pair of parenthesis and implementation we can convert this into a Lambda Expression

() -> {  System.out.println("In thread t3"); }   

and since it is having the single statement in the body, we can remove this parathesis as well

() -> System.out.println("In thread t3")

In This is our first cute Lambda

The most important part of this code is the function’s body and parameter List(No Parameter here) that is all we are having in this lambda.
Just don’t forget, that we can only Convert Lambdas for the Interfaces having only one Abstract Method, then only the compiler will be able to Guess everything we talked about because there will not be any ambiguity
In our case the Interface implementation we are supplying is Runnable, Having only one method RUN.

The most important point to note here is that Lambda expression can be written only for those interfaces which have single abstract method.

And, this kind of interfaces having only one abstract method is called Functional Interfaces.

Functional Interfaces

Functional Interface can be explained as an interface whose implementation is generally provided using Lambda. Technically, A Functional Interface is an interface with a single abstract method.

For example, a simple functional interface can be defined as follows :

@FunctionalInterface
public interface MyFunctionalInterface{
	
	public void myMethod();
}

If there is more than one abstract method in an interface it will not be called a functional Interface. The reason being the execution of Lambda without any ambiguity.

The implementation of the above functional interface or the single abstract method of the above functional interface using lambda can be demonstrated as follows:

package com.basicsstrong.fp;
public class FunctionalnterfaceDemo {
	public static void main(String[] args) {
		myFunctionalInterface fun1= () -> System.out.println("Hello");		                 fun1.myMethod();
}
}		

Here you’ll see, when we write a lambda, we do not care about the name of the method we are implementing. This is the reason functional interfaces are allowed to have a single abstract method as there is always a single method to be implemented using lambda. After implementing the method, we invoke the function as we always do.

So, we are calling the myMethod on the interface reference to get the myMethod executed. It displays “Hello”. The notable thing of this discussion is that In JAVA 8, functions can be viewed analogously to variable assignments.

The above method does not contain any parameters but if we want to pass the behaviour (Lambda) directly as a parameter then we can do so as follows :

package com.basicsstrong.fp;
public class FunctionalnterfaceDemo {
	public static void main(String[] args) {
            onTheFly(()->System.out.println("Hello to FUN!"));
}
      public static void onTheFly(myFunctionalInterface fun) {
             fun.myMethod();
     }
}

Thus it must be clearly understood with this blog that how functional interface is an important concept of JAVA 8 and how it is used for executing Lambda expression. In the next blog, we will discuss how JAVA 8 implemented Lambda under the Hood.