Lambda 表达式

(参数列表) ‐> { 代码语句 }
// Lambda表达式的书写形式
Runnable run = () -> System.out.println("Hello World");// 1
ActionListener listener = event -> System.out.println("button clicked");// 2
Runnable multiLine = () -> {// 3 代码块
    System.out.print("Hello");
    System.out.println(" Hoolee");
};
BinaryOperator<Long> add = (Long x, Long y) -> x + y;// 4
BinaryOperator<Long> addImplicit = (x, y) -> x + y;// 5 类型推断

使用前提

有且仅有一个抽象方法的接口,称为"函数式接口"。

函数式接口

一旦使用该注解来标记接口,编译器将会强制检查该接口是否确实有且仅有一个抽象方法,否则编译将会报错。

@FunctionalInterface
public interface SuperRunnable {
    void superRun();
}
public static void main(String[] args) {
    superRun(()-> System.out.println("hello world"));
}
private static void superRun(SuperRunnable sr){
    sr.superRun();
}
接口 参数 返回值 示例
Predicate<T> T Boolean 接收一个参数,返回一个布尔值
Consumer<T> T void 接受一个参数,无返回
Function<T, R> T R 接受一个参数,返回一个值
Supplier<T> None T 无参数 返回一个值

Lambda JVM层实现

Java编译器将Lambda表达式编译成使用表达式的类的一个私有方法,然后通过invokedynamic指令调用该方法。所以在Lambda表达式内,this引用指向的仍是使用表达式的类。

方法引用

应用