Lambda expression in Java 8

Lambda expression is one of the core feature introduced in Java 8 as it provides a way to achieve functional programming in an object oriented programming language. It is anonymous function without having modifiers and return type. In other words, it simply provides a definition to a single abstract method defined within an interface called as Functional interface.

Point to remember:

– It provides a way to achieve functional programming in Java

-A Lambda expression is anonymous function having no modifiers and return type.

– It uses functional interfaces as its base to implement functional programming in Java. Without functional interface it cannot be implemented.

-It uses arrow operator or lambda operator to tell the compiler it is a Lambda expression

Syntax:

lambda expressions

These are following features of a lambda expression:

another lambda
No return type: Unlike function, in lambda expression, we don’t provide the return type. We simply write () -> {}

No Modifiers: Another important aspect of Lambda expression is, no modifier is required to mention.

The above two aspects indirectly depends on abstract method of a functional interface. Lambda Expression indirectly references to that type.

Optional Argument type : It is not mandatory to provide datatype to the parameter, but if one does then parenthesis would be mandatory

Optional Parenthesis : if there is a single argument then putting parenthesis would be optional
Optional curly braces and return type : if there is a single statement in the expression body then there is no need to put curly braces and return statement(if have).

 

 

Before Lambda Expression:

create a function:

void cube(int x) {
System.out.println("cube :"+ x*x*x);

}

create an object to call that function:

Test obj = new Test();

Invoke it

obj.cube(3);

 

After Lambda Expression:

Import Function (A predefined functional interface)

import java.util.function.Function;

Create a Lambda expression:

Function<Integer,Integer> cube = x -> x*x*x;

call its apply abstract method

System.out.println("This is the cube of "+ x + ":"+ cube.apply(x));

Leave a Reply