Lambda Expressions
Lambda Expressions are added in JDK8 which have the greater significantly enhancement like Generics in Java
They add new syntax elements that increase the expressive power of the language.
new capabilities being incorporated into the API library like parallel processing capabilities of multi-core environments,handling of for-each style operations, and the new stream API, which supports pipeline operations on data.
Provides the default method, which lets you define default behavior for an interface method, and the method reference which lets to refer a method without executing it.
Introducing Lambda Expressions
lambda expression-
- It is an anonymous method means unnamed which is not executed it's own.
It is used to implement a method defined by a functional interface.
It results in a form of anonymous class.
These are also commonly referred to as closures.
functional interface-
- It is an interface which contains only one abstract method which specifies the intended purpose of the interface.
- Means it represents only one action.
Lambda Expression
- This expression introduces new syntax and a new operator -> which is called as lambda operator or arrow operator which is verbalized as becomes orgoes to.
The left side of the operator contains parameters required for lambda expression if no one needed then it will be empty.
The right side of operator contains _lambda body_to specify the actions of the lambda expression.
The lambda body can be two types
With a single expression
A block of code
Examples:
- () -> 123.45-it doesn't take parameters as empty braces and it will return a double value 123.45
- () -> Math.random() * 100-This also doesn't take parameters but returns the value which is multiplied by 100 with a random number.
- (n) -> (n % 2)==0-It takes a parameter n which returns true if it is even otherwise false.
Functional Interfaces
- It contains only one abstract method although all the methods in interface are implicitly abstract but there is a option in JDK8 where we can create a default method for an interface.
- In this we do not maintain a default method.
Example
interface MyNumber
{
double getValue();
}
Here MyNumber is the functional interface with a abstract method called getValue() which have no default implementation thus there is no need to specify abstract keyword.
- A lambda expression can not execute itself only if the abstract method defined by the functional interface that specifies its target type.
- With the reference of the functional interface only we can assign a lambda expression and we get the value by its abstract method as follows.
//example for lambda expression
interface MyNumber
{
double getValue();
}
public class LAmbdaExpressionExample1
{
public static void main(String []args)
{
MyNumber num=() -> 1.2434;
System.out.println(num.getValue());
}
}
Output:
1.2434
- In order for a lambda expression to be used in a target type context , the type of the abstract method and the type of the lambda expression must be compatible.
//type incompatible
interface MyNumber
{
int getValue();
}
public class LambdaExpressionExample2
{
public static void main(String []args)
{
MyNumber num=() -> 1.2434;
System.out.println(num.getValue());
}
}
This will throw an error as conversation problem from double to int.
Examples for Lambda Expressions
// Demonstrate a simple lambda expression.
// A functional interface.
interface MyNumber {
double getValue();
}
interface NumericTest
{
boolean test(int n);
}
public class LambdaExpressionExample3 {
public static void main(String args[])
{
MyNumber myNum; // declare an interface reference
myNum = () -> 123.45; //just a constant value
// Call getValue(), which is provided by the previously assignedlambda expression.
System.out.println("A fixed value: " + myNum.getValue());
// Here, a more complex expression is used.
myNum = () -> Math.random() * 100;
// These call the lambda expression in the previous line.
System.out.println("A random value: " + myNum.getValue());
System.out.println("Another random value: " + myNum.getValue());
NumericTest isEven = (n) -> (n % 2)==0; //assign an expression to a reference of NumericTest which evaluates whether a number is even or not
if(isEven.test(10))
System.out.println("10 is Even");
NumericTest isNonNeg = (n) -> n >= 0;
if(isNonNeg.test(1)) System.out.println("1 is non-negative");
if(!isNonNeg.test(-1)) System.out.println("-1 is negative");
}
}
Output:
A fixed value: 123.45
A random value: 33.142629343610416
Another random value: 11.01390869842005
10 is Even
1 is non-negative
-1 is negative
// Demonstrate a lambda expression that takes two parameters.
interface NumericTest2
{
boolean test(int n, int d);
}
public class LambdaDemo4
{
public static void main(String args[])
{
// This lambda expression determines if one number is
// a factor of another.
NumericTest2 isFactor = (n, d) -> (n % d) == 0;
if(isFactor.test(10, 2))
System.out.println("2 is a factor of 10");
if(!isFactor.test(10, 3))
System.out.println("3 is not a factor of 10");
}
}
Output:
2 is a factor of 10
3 is not a factor of 10
Block Lambda Expressions
- In all examples lambdas have only single expressions which are called as expression bodies , and lambdas that have expression bodies are sometimes called expression lambdas.
Expression bodies-
- In this the right side of the lambda operator must consist of a single expression.
Expression lambdas-
- In this we can use more than one lambda expression , which consists of block of code called as block body.
- Lambdas that have block bodies are sometimes referred to as block lambdas.
- The main difference is in this we have to explicitly return values as follows
// A block lambda that computes the factorial of an int value.
interface NumericFunc {
int func(int n);
}
public class BlockLambdaDemo
{
public static void main(String args[])
{
// This block lambda computes the factorial of an int value.
NumericFunc factorial = (n) ->
{
int result = 1;
for(int i=1; i <= n; i++)
result = i * result;
return result;
};
System.out.println("The factoral of 7 is " + factorial.func(7));
System.out.println("The factoral of 5 is " + factorial.func(5));
}
}
Output:
The factoral of 7 is 5040
The factoral of 5 is 120
// A block lambda that reverses the characters in a string.
interface StringFunc
{
String func(String n);
}
public class BlockLambdaDemo2
{
public static void main(String args[])
{
// This block lambda reverses the characters in a string.
StringFunc reverse = (str) ->
{
String result = "";
int i;
for(i = str.length()-1; i >= 0; i--)
result += str.charAt(i);
return result;
};
String string="Helloo";
StringFunc reverse1 = (str) -> new StringBuffer(string).reverse().toString(); //single expression
System.out.println("Lambda reversed is " + reverse.func("Lambda"));
System.out.println("Expression reversed is " + reverse.func("Expression"));
System.out.println("Helloo reversed is "+reverse1.func("Helloo"));
}
}
Output:
Lambda reversed is adbmaL
Expression reversed is noisserpxE
Helloo reversed is oolleH