Lambda Expressions
1.Syntax
p -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25
p -> {
return p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25;
}
2.Scope
import java.util.function.Consumer;
public class LambdaScopeTest {
public int x = 0;
class FirstLevel {
public int x = 1;
void methodInFirstLevel(int x) {
Consumer<Integer> myConsumer = (y) ->
{
System.out.println("x = " + x); // Statement A
System.out.println("y = " + y);
System.out.println("this.x = " + this.x);
System.out.println("LambdaScopeTest.this.x = " +
LambdaScopeTest.this.x);
};
myConsumer.accept(x);
}
}
public static void main(String... args) {
LambdaScopeTest st = new LambdaScopeTest();
LambdaScopeTest.FirstLevel fl = st.new FirstLevel();
fl.methodInFirstLevel(23);
}
}
Output:
x = 23
y = 23
this.x = 1
LambdaScopeTest.this.x = 0
3.Target Typing
- Variable declarations - Assignments - Return statements - Array initializers - Method or constructor arguments - Lambda expression bodies - Conditional expressions, ?: - Cast expressions
4.Serialization
You can serialize a lambda expression if its target type and its
captured arguments are serializable. However, like inner classes, the
serialization of lambda expressions is strongly discouraged.