Lambda表达式

Lambda表达式

Lambda表达式产生的意义:
  • ​ 避免匿名内部类定义过多。
  • ​ 可以让代码看起来更简洁。
  • ​ 去掉了一堆没有意义的代码,只留下核心逻辑。
函数式接口的定义:任何接口,如果只包含唯一一个抽象方法,那么他就是一个函数式接口。
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}
  • 对于函数式接口,我们可以通过lambda表达式老创建该接口的对象。

示例:

package lambda;

/**
 * @Description
 * @Author wangkui
 * @Date 2022-07-28 16:25
 * @Version 1.0
 */
public class TestLambda2 {
    public static void main(String[] args) {
        
        ILove love = (int a) -> System.out.println("i love you -->" + a);
        //继续简化.
        love = a -> System.out.println("i love you -->" + a);
        love.love(1);
    }
}

interface ILove {
    /**love
     * @param a a
     */
    void love(int a);
}

class Live implements ILove {

    @Override
    public void love(int a) {
        System.out.println("i love you -->" + a);
    }
}

posted @ 2022-07-28 23:21  昨夜风雨声  阅读(20)  评论(0)    收藏  举报  来源