Lambda Expression - RichardDanielOliva/java-learning-wiki GitHub Wiki
A Lambda expression is an anonymous function, an abstract method, that is, a method that is only defined in an interface but not implemented, and** that is the key** of the lambda functions, as it is not implemented, the programmer can implement it where he thinks convenient without having inherited from the interface.
Syntax
(Parameters)->{Body}
- The lambda operator (->) separates the declaration of parameters from the declaration of the body of the function.
- Parameters:
- When you have only one parameter you do not need to use parentheses.
- When you do not have parameters, or when you have two or more, it is necessary to use parentheses.
- Lambda body:
- When the body of the expression lambda has a single line it is not necessary to use the keys and they do not need to specify the return clause in case they have to return values.
- When the body of the expression lambda has more than one line it is necessary to use the keys and it is necessary to include the return clause in case the function must return a value.
Example
FunctionalInterface
public interface FigureSquare {
//abstract method to add 2 numbers, which will be implemented by the programmer from a Lambda expression
public double calculateArea(int side, int height);
}
public class TestLambdas {
public static void main(String[] args) {
int x = 10;
int y = 5;
//the interface method is implemented with a lambda expression
FigureSquare geometry = (int height, int length) -> {
return height * length;
};
FigureSquare triangle = (int height, int length) -> {
return height * length /2;
};
//the method is used with the implementation and the corresponding values are sent to you
double areaSquare = square.calculateArea(x, y);
double areaTriangle = triangle.calculateArea(x, y);
}
}
Uses of lambda expressions
As we have seen before, lambdas can be used wherever the type of accepted parameters is a functional interface.
This is the case of many of the functionalities offered by java.util.stream, a new API that appears with Java 8, which allows the functional programming over a flow of values without structure.