Lambda 表达式,也可称为闭包。Lambda允许把函数作为一个方法的参数(函数作为参数传递进方法中,相当于将匿名子类对象传入进入,该对象实现的接口中仅能有一个抽象方法)
- 可选类型声明:不需要声明参数类型,编译器可以统一识别参数值。
- 可选的参数圆括号:一个参数无需定义圆括号,但多个参数需要定义圆括号。
- 可选的大括号:如果主体包含了一个语句,就不需要使用大括号。
- 可选的返回关键字:如果主体只有一个表达式返回值则编译器会自动返回值,大括号需要指定明表达式返回了一个数值。
- lambda表达式只能引用标记了 final 的外层局部变量,不写也行,但是必须不可被后面的代码修改(即隐性的具有 final 的语义)
案例一
public class Java8Tester {
public static void main(String args[]){
Java8Tester tester = new Java8Tester();
// 类型声明
MathOperation addition = (int a, int b) -> a + b;
//MathOperation声明了一个对象,并且重写了里面的方法operation
//该重写的方法需要两个参数,这与接口中的抽象方法的参数数量一致
//它的返回值是a+b
// 不用类型声明
MathOperation subtraction = (a, b) -> a - b;
// 大括号中的返回语句
MathOperation multiplication = (int a, int b) -> { return a * b; };
// 没有大括号及返回语句
MathOperation division = (int a, int b) -> a / b;
//传入哪个实现类对象,执行哪个实现类对象重写的方法
System.out.println("10 + 5 = " + tester.operate(10, 5, addition));
System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));
System.out.println("10 / 5 = " + tester.operate(10, 5, division));
// 不用括号
GreetingService greetService1 = message ->
System.out.println("Hello " + message);
// 用括号
GreetingService greetService2 = (message) ->
System.out.println("Hello " + message);
greetService1.sayMessage("Runoob");
greetService2.sayMessage("Google");
}
private int operate(int a, int b, MathOperation mathOperation){
return mathOperation.operation(a, b);
}
}
interface MathOperation {
int operation(int a, int b);
}
interface GreetingService {
void sayMessage(String message);
}
案例二
public class Test {
public static void main(String args[]) {
Integer[] arr = { 2, 3, 6, 7, 9 };
// 这里使用了Lambda表达式
// 由源码可知,forEach需要传入一个参数action
// 由源码可知,action有一个抽象方法accept和一个有方法体的方法
// 以这种传入方法(Lambda表达式)的形式,相当于往里面传入了一个匿名对象,并重写了这个accept方法,
// 通过forEach代码可知,里面调用了action的重写了的方法accept
Arrays.asList(arr).forEach(x -> System.out.println(x));
}
}
default void forEach(Consumer<? super T> action) {
//该方法位于Iterable接口中,public interface Iterable<T> {...}
//T由其实现类去指定如List<String> list = new ArrayList();
Objects.requireNonNull(action);
for (T t : this) {//这里的this对应的是集合
action.accept(t);
}
}
public interface Consumer<T> {
void accept(T t);
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> {
accept(t);
after.accept(t);
};
}
}
参考链接: Java 8 Lambda 表达式