Lambda Expression
- Since first java version(1.0) many new features were added but later in JDK5 added fundamentally changing the way that code is written.
- In these JDK8 lambda expression is introduced due to 2 reasons.
- First is add the new syntax that increase the expressive power of the language where constructs are followed in certain order.
- Second, the new capabilities were introduced into the API library.
- In final analysis the generics reshaped java several years ago and now lambda expressions reshaped the java today.
- And over few years the lambda expressions are developed in C# and C++.
Introducing Lambda Expressions:
- It is used to implement a method defined by a functional interface.It is form of anonymous class .
lambda expressions is also referred as closures.
Functional interface contains one and only abstract method.It represent a single action.
A functional interface refers to SAM type(Single Abstract Method)
Lambda expressions fundamentals:
- The new syntax element is used in java language is introduced.
- The left side specifies the any parameter required by lambda expressions.
The right side specifies the lambda body which shows the actions of lambda expressions.
It define two types of lambda bodies;
First as single expressions and second as block of code
And these first types as single expression as,
() -> 123.45
This lambda expression takes no parameters, thus the parameter list is empty.
It returns the constant value 123.45.
Therefore the method,
double myMeth() { return 123.45; }
When a lambda expression requires a parameter, it is specified in the parameter list on
the left side of the lambda operator,(n) -> (n % 2)==0
These lambda expressions returns true only if the parameter of n is even.