Lambda Expressions
A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.
Syntax
The simplest lambda expression contains a single parameter and an expression:
parameter -> expression
To use more than one parameter, wrap them in parentheses:
(parameter1, parameter2) -> expression
Expressions are limited. They have to immediately return a value, and they cannot contain variables, assignments or statements such as if or for. In order to do more complex operations, a code block can be used with curly braces. If the lambda expression needs to return a value, then the code block should have a return statement.
(parameter1, parameter2) -> { code block }
Important features
The body of a lambda expression can contain zero, one or more statements.
When there is a single statement curly brackets are not mandatory and the return type of the anonymous function is the same as that of the body expression.
When there are more than one statements, then these must be enclosed in curly brackets (a code block) and the return type of the anonymous function is the same as the type of the value returned within the code block, or void if nothing is returned.
Lambda expressions are just like functions and they accept parameters just like functions.
Example:
// A Java program to demonstrate simple lambda expressions
import java.util.ArrayList;
class Test
{
public static void main(String args[])
{
// Creating an ArrayList with elements
// {1, 2, 3, 4}
ArrayList<Integer> arrL = new ArrayList<Integer>();
arrL.add(1);
arrL.add(2);
arrL.add(3);
arrL.add(4);
// Using lambda expression to print all elements
// of arrL
arrL.forEach(n -> System.out.println(n));
// Using lambda expression to print even elements
// of arrL
arrL.forEach(n -> { if (n%2 == 0) System.out.println(n); });
}
}
Output
1
2
3
4
2
4
Note that lambda expressions can only be used to implement functional interfaces. In the above example also, the lambda expression implements Consumer Functional Interface.
Lambda expressions are added in Java 8 and provide below functionalities.
Enable to treat functionality as a method argument, or code as data.
A function that can be created without belonging to any class.
A lambda expression can be passed around as if it was an object and executed on demand.
Example
// Java program to demonstrate lambda expressions
// to implement a user defined functional interface.
// A sample functional interface (An interface with
// single abstract method
interface FuncInterface
{
// An abstract function
void abstractFun(int x);
// A non-abstract (or default) function
default void normalFun()
{
System.out.println("Hello");
}
}
class Test
{
public static void main(String args[])
{
// lambda expression to implement above
// functional interface. This interface
// by default implements abstractFun()
FuncInterface fobj = (int x)->System.out.println(2*x);
// This calls above lambda expression and prints 10.
fobj.abstractFun(5);
}
}
Output
10
Difference between anonymous class and lambda expression
Anonymous Class | Lambda Expression |
---|---|
Anonymous class is a class that can contain constructors, variables and methods | Lambda expression is an anonymous method |
An anonymous class object generates a separate class file after compilation that increases the size of a jar file | A lambda expression is converted into a private method. It uses invokedynamic bytecode instruction to bind this method dynamically, which saves time and memory. |
We use this keyword to represent the current class in lambda expression | In the case of an anonymous class, this keyword can represent that particular anonymous class. |
Anonymous classes can be used in case of more than one abstract method | Lambda expression specifically used for functional interfaces. |
We need to provide the function body only in lambda expression | In the case of an anonymous class, we need to write the redundant class definition. |