Java8的Lambda和方法引用(Lambda and method reference of Java 8)

当:

1、成员方法或构造方法中的形参是接口(Interface)

2、该接口为函数式接口,即抽象方法只有一个

在方法实现的时候可以采用的方式有:

1、传统的方式实现(也适用于非函数式接口)

创建该接口的匿名内部类并重写接口方法

        //方式一
        Thread lambda1 = new Thread(new Runnable() {
            @Override
            public void run() {
                RunnableImpl r1 = new RunnableImpl();
                r1.sellTick();

            }
        }
        );

使用lambda表达式要点即  采用()->{} 的方式,注意对lambda表达式简化后的理解

        //方式二
        Thread lambda2 = new Thread(() -> {
            r1.sellTick();
        }
        );

        //方式二改写
        Thread lambda3 = new Thread(() -> r1.sellTick());

3、使用方法引用

前提是有一个已经实现的方法,且该方法满足接口抽象方法的形参和返回值。可以采用方法引用的方式传入接口,极大简化代码

        //方式三
        Thread thread = new Thread(new RunnableImpl()::sellTick);

总结:无论是Lambda还是方法引用,核心就是必须满足接口方法中的形参和返回值。

注意:采用方法引用的时候,接口方法无返回值,则方法引用中有无返回值都可以实现编译执行;

————————

When:

1. The formal parameter in a member method or constructor is an interface

2. This interface is a functional interface, that is, there is only one abstract method

The following methods can be adopted when implementing the method:

1. Traditional implementation (also applicable to non functional interfaces)

Create an anonymous inner class of the interface and override the interface method

        //方式一
        Thread lambda1 = new Thread(new Runnable() {
            @Override
            public void run() {
                RunnableImpl r1 = new RunnableImpl();
                r1.sellTick();

            }
        }
        );

The key point of using lambda expression is to use () – & gt; Pay attention to the simplified understanding of lambda expression

        //方式二
        Thread lambda2 = new Thread(() -> {
            r1.sellTick();
        }
        );

        //方式二改写
        Thread lambda3 = new Thread(() -> r1.sellTick());

3. Use method reference

The premise is that there is an implemented method, and the method meets the formal parameters and return values of the interface abstract method. The interface can be passed in by means of method reference, which greatly simplifies the code

        //方式三
        Thread thread = new Thread(new RunnableImpl()::sellTick);

Summary: whether lambda or method reference, the core is to meet the formal parameters and return values in the interface method.

Note: when using method reference, if the interface method has no return value, the compilation can be realized whether there is a return value in the method reference or not;