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.
To create a lambda expression, we specify input parameters (if there are any) on the left side of the lambda
operator ->, and place the expression or block of statements on the right side of lambda operator.
Example
The lambda expression (x, y) -> x + y specifies that lambda expression takes two arguments
x and y and returns the sum of these.
(parameters) -> expression
(x, y) -> x + y
A method (or function) in Java has 4 main parts:
A Lamdba expressions in Java has only body and parameters list parts:
To use lambda expression, you need to either create your own functional interface or use the pre defined functional interface provided by Java. An interface with only single abstract method is called functional interface(or Single Abstract method interface), for example: Runnable, callable, ActionListener etc.
A lambda expression can have zero, one or more parameters.
(x, y) -> x + y
(x, y, z) -> x + y + z
The body of the lambda expressions can contain zero, one or more statements. If the body of lambda expression has a single statement curly brackets are not mandatory. When there is more than one statement in the body then these must be enclosed in curly brackets.
(parameters) -> { statements; }
() -> expression
a -> return a * a;
In the given example, we are iterating over the list and printing all the list elements in the standard output. We can perform any desired operation in place of printing them.
List<String> pointList = new ArrayList();
pointList.add("1");
pointList.add("2");
pointList.forEach( p -> { System.out.println(p); } );