A lambda expression is a litteral expression that implements a functional interface (interface with only one method).
Because a functional interface contains only one abstract method, a lambda expression omit the name of the implemented method.
Usage:
Sort of closure (first class function).
The lambda expression's parameter and return types are parsed, matched or adapted to a functional interface.
As a lambda expression looks a lot like a method declaration, you can consider lambda expressions as anonymous methods—methods without a name.
A lambda expression consists of the following:
p -> p.getGender() == Person.Sex.MALE && p.getAge() >= 18 && p.getAge() <= 25
// or
email -> System.out.println(email)
p -> {
return p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25;
}
Lambda expressions are lexically scoped.
They:
Declarations in a lambda expression are interpreted just as they are in the enclosing environment. Consequently, you can directly access fields, methods, and local variables of the enclosing scope.
See demo
To determine the type of a lambda expression, the Java compiler uses the target type (the argument data type) of the context or situation in which the lambda expression was found.
Therefore you can only use lambda expressions only where the Java compiler can determine a target type such as
To use a lambda expression, the type of the variable need to be a functional interface. IntegerMath is a functional interface because it has only one method.
public class Calculator {
interface IntegerMath {
int operation(int a, int b);
}
public int operateBinary(int a, int b, IntegerMath op) {
return op.operation(a, b);
}
public static void main(String... args) {
Calculator myApp = new Calculator();
IntegerMath addition = (a, b) -> a + b;
IntegerMath subtraction = (a, b) -> a - b;
System.out.println("40 + 2 = " +
myApp.operateBinary(40, 2, addition));
System.out.println("20 - 10 = " +
myApp.operateBinary(20, 10, subtraction));
}
}
retrolambda - Backport of Java 8's lambda expressions to Java 7, 6 and 5