Lambda 表达式

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

使用前提

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

函数式接口

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

@FunctionalInterfacepublic 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>TBoolean接收一个参数,返回一个布尔值
Consumer<T>Tvoid接受一个参数,无返回
Function<T, R>TR接受一个参数,返回一个值
Supplier<T>NoneT无参数 返回一个值

Lambda JVM层实现

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

通过一些编译优化技术,如果分析得到这个类可以是无状态,就可以内联优化,否则每次执行就必须创建这个动态类的实例

方法引用

应用