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:

 @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

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:

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.

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

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

Leave a Reply