28/05/2018 Lambda Expressions in Java 8 - GeeksforGeeks
lambda operator -> body
where lambda operator can be:
Zero parameter:
() -> [Link]("Zero parameter lambda");
One parameter:–
(p) -> [Link]("One parameter: " + p);
It is not mandatory to use parentheses, if the type of that variable can be inferred from the context
Multiple parameters :
(p1, p2) -> [Link]("Multiple parameters: " + p1 + ", " + p2);
Please note: Lambda expressions are just like functions and they accept parameters just like functions.
// A Java program to demonstrate simple lambda expressions
import [Link];
class Test
{
public static void main(String args[])
{
// Creating an ArrayList with elements
// {1, 2, 3, 4}
ArrayList<Integer> arrL = new ArrayList<Integer>();
[Link](1);
[Link](2);
[Link](3);
[Link](4);
// Using lambda expression to print all elements
// of arrL
[Link](n > [Link](n));
// Using lambda expression to print even elements
// of arrL
[Link](n > { if (n%2 == 0) [Link](n
}
}
Run on IDE
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.
[Link] 2/4