Lambda Expression
Lambda expressions are introduce in Java 8 and are touted to be the biggest feature of Java 8.
Lambda expressions facilitates functional programming,and simplifies the development a lot.
Syntax
A lambda expression is characterized by the following syntax.
parameter -> expression body
Following are the important characteristics of a lambda expression.
- Optional type declaration–No need to declare the type of parameter.The compiler can inference the same from the
value of the parameter. - Optional parenthesis
()
around parameter–No need to declare a single parameter in parenthesis.For multiple
parameters,parentheses are required. - Optional curly braces
{}
–No need to user curly braces in expression body if the body contains a single
statement. - Optional return keyword–The compiler automatically
returns
the value if the body has a single expression to
return the value.Curly braces are required
to indicate that expression return a value.
Lambda Expressions Example
1 | public class LambdaTest { |
Verify the result
Compile the class using javac
compiler as follows:
$javac LambdaTest.java && java LambdaTest
It should produce the following output:
1 | 10 + 5 =15 |
Following are the important points to be considered in the above example.
- Lambada expressions are used primary to define inline implementations of a functional interface,an interface
witha single methode only
. - Lambda expressions
eliminates the need of anonymous class
and gives a very simple powerful functional programming
capability to Java.