Functional Interface and Lambda Expression

 

Welcome to the tutorial of Functional Interface and Lambda expression. In this tutorial we will discuss fundamental concept of functional interface and lambda expression.

Functional Interface :

Functional Interface is just a interface with one abstract method, but it  can have any number of default and static method. Runnable and Comparable interface are the example of functional interface.

Example:

public interface TestInterface {
public abstract void show(int n);
public static void hello() {
System.out.println("static method");
}
public default void test() {
System.out.println("default method");
}
}

 @FunctionalInterface Annotation:

We use @Functional annotation with a functional interface , it ensure that this interface can’t have more than one abstract method. If we define more than one abstract method in in this interface then compiler shows an error ‘Invalid ‘@FunctionalInterface’ annotation

@FunctionalInterface
public interface TestInterface {
public abstract void show(int n);
public static void hello() {
System.out.println("static method");
}
public default void test() {
System.out.println("default method");
}
}

Lambda Expression:

Lambda expression is an anonymous method (a method without name) which are used to implements the abstract method of functional interface.

Lambda expression introduces a new operator in java called ARROW ( -> ) operator. It divides the lambda expression in two parts:

(n) - > System.out.println(n);

Left side specify required parameter of implemented method, it can be empty if no parameter is required. Right side of lambda expression specify the action of the lambda expression (body of implemented method);

In java 7 when we want to use functional interface in our class then  either we had to implement that interface and override abstract method of that interface or using the anonymous class.

Example 1:  Let’s create a thread without lambda expression.

public class LambdaTest implements Runnable{
  public void run() {
    System.out.println("thread running");
  }    
 public static void main( String[] args ){
   	 Thread t = new Thread(new LambdaTest()); 
   	 t.start();   	 
   }
}

But in java 8 , It is not necessary  to implement functional interface in our class. We can use it with lambda expression.

Example 2 : Thread creation with lambda expression

public class LambdaTest{
public static void main( String[] args ){
Runnable run = () -> { 
System.out.println("Thread");
};
/* you can also write like this

Runnable run = () -> System.out.println("Thread");
*/
 Thread t = new Thread(run);
 t.start();
 }
}

From the above example , we have noticed that thread creation with lambda expression is simple and having less and clean code.

Leave a Reply