- Lambda Expression is a mathematical term and big change in calculus in mathematics.
- Lambda has been introduced in 1930.
- Lambda expression is a new feature which is introduced in Java 8.
- A lambda expression is an anonymous function. A function that doesn’t have a name and doesn’t belong to any class.
- Lambda expression was first introduced in LISP programming language.
Lambda Expression is just anonymous function/nameless function, Which is
not having any name, return type, modifiers.
It is anonymous function
Anonymousè
1. No name
2. Without return type
3. Without modifiers
Advantage
of Lambda Expression
- We can enable functional programming in java.
- We can reduce length of the code so that readability will be improved.
- We can resolve complexity of anonymous inner class until some intent.
- We can handle procedures/function just like values.
- We can pass procedures/functions as arguments.
- Easier to use updated APIs and Libraries.
- Enable support for parallel processing.
Example 1: Without using Lambda expression with no parameter.
public void test()
{
System.out.println("Hi Java");
}
Lambda Expressions: It is use special symbols (à) and curly braces are optional ({}) in this example
() -> { System.out.println("Hi Java"); }
() -> System.out.println("Hi Java");
Example 2: Without using Lambda expression with multiple parameter.
public void test( int i , int j)
{
System.out.println(i+j);
}
- If the type of the parameter can be decided by compiler automatically based on the context then we can remove types also.
- The above Lambda expression we can rewrite as (i,j) ->sop (i+j);
With Lambda Expression with multiple parameter.
(int i , int j) -> { System.out.println(i+j); }
or
(i,j) -> System.out.println(i+j);
Example 3: Without using Lambda expression to return.
public int square(int n)
{
return n*n;
}
With Lambda Expression
(int n) ->{return n*n;}
or
(int n )->n*n;
or
(n)->n*n;
or
n->n*n;
Note:
- Without curly braces we cannot use return keyword. Compiler will consider returned value automatically.
- Within curly braces if we want to return some value compulsory we should use return statement.
Example 4: With out using Lambda expression how to get length.
public void test(String s)
{
return s.length();
}
With Lambda Expression
s-> s.length();
Note:
- We can see that the with Lambda expression code and without Lambda expression.
- We can see that Lambda expression is less code
0 Comment to "Lambda Expression"
Post a Comment