1.语法(Syntax)
- 以逗号分隔的参数列表,外侧用括号来包裹。
- 只有一个参数可以不套括号
- 参数与函数体用 -> 连接(The arrow token)
- 函数体不套{}的话自动return表达式结果
p -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25
- void类型可以用不套括号写一句表达式
email -> System.out.println(email)
lambda表达式是为了
1.只有一个函数的interface不需要定义一个类来继承方法
2.不需要在使用时创建对象
2.使用例子
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();
// Override the interface with Lambda Expression
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));
}
}
Lambda对于作用域的变量的访问
import java.util.function.Consumer;
public class LambdaScopeTest {
public int x = 0;
class FirstLevel {
public int x = 1;
void methodInFirstLevel(int x) {
// The following statement causes the compiler to generate
// the error "local variables referenced from a lambda expression
// must be final or effectively final" in statement A:
//
// x = 99;
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);
}
}
需要注意的有两点
1.Lambda可以直接获取method里的变量x,对于在类作用域里的变量x,用到了this,比如this.x, LambdaScopeTest.this.x。
2.x = 99会出错,因为Lambda所用到的Local Variables必须是fina或者effectively final的,不能在初始化之后修改。
另外,以上例子中Lambda参数y不能改名字为“x”,因为Lambda没有新的作用域。
// Error:variable x is already defined in method methodInFirstLevel(int)
Consumer<Integer> myConsumer = (x) -> {
// ...
}