Lamda 表达式

1 什么是Lambda

Lambda 表达式是一种匿名函数,简单地说,它是没有声明的方法,也即没有访问修饰符、返回值声明和名字。它可以写出更简洁、更灵活的代码。作为一种更紧凑的代码风格,使 Java 语言的表达能力得到了提升。

2 Lambda 语法

(params) -> expression
(params) -> statement
(params) -> { statements }

3 函数式接口

Lambda是建立在函数式接口的基础上的,先了解什么是函数式接口。

(1) 只包含一个抽象方法的接口,称为函数式接口;

(3) 可以通过 Lambda 表达式来创建该接口的对象;

(3) 我们可以在任意函数式接口上使用 @FunctionalInterface 注解,这样做可以检测它是否是一个函数式接口,同时 javadoc 也会包含一条声明,说明这个接口是一个函数式接口。

在实际开发者有两个比较常见的函数式接口:Runnable接口,Comparator接口

4 普通外部类向Lambda表达式演进过程

实例1

/**
 * @author Latiny
 * @version 1.0
 * @description: Lambda表达式的演进
 * @date 2019/8/21 15:18
 */

public class LambdaDemo {

    public static void main(String[] args) {

        // 1 外部接口实现类
        Animal human = new Human();
        human.move();

        // 2 内部静态类
        Animal snake = new Snake();
        snake.move();

        // 3 内部匿名类
        Animal bird = new Animal(){
            @Override
            public void move() {
                System.out.println("Flying");
            }
        };
        bird.move();

        // 4 Lambda 表达式
        Animal fish = () -> {
            System.out.println("Swimming");
        };
        fish.move();
    }

    /**
     * 2 内部静态实现类
     */
    static class Snake implements Animal {

        @Override
        public void move() {
            System.out.println("Crawling");
        }
    }
}

/**
 * 接口
 */
interface Animal {

    void move();
}

/**
 * 1 外部接口实现类
 */
class Human implements Animal {

    @Override
    public void move() {
        System.out.println("Walking");
    }
}
View Code

实例2 

public class LambdaTest {

    public static void main(String[] args) {

        // 1 内部匿名类
        Calculate calculate = new Calculate(){
            @Override
            public int add(int a, int b) {
                return a + b;
            }
        };
        calculate.add(10, 20);

        // 2 Lambda 表达式
        calculate = (a, b) -> {
            return a + b;
        };
        calculate.add(3, 7);
    }

}

/**
 * 接口
 */
interface Calculate {

    int add(int a, int b);
}
View Code

5 Lambda表达式在Thread中的应用

    public static void main(String[] args) {

        new Thread(() -> {
            int i = 1;
            while (i <= 100) {
                System.out.println(Thread.currentThread().getName() + "--->" + i);
                i++;
            }
        }, "Human").start();

        Runnable runnable = () -> {
            int i = 1;
            while (i <= 100) {
                System.out.println(Thread.currentThread().getName() + "--->" + i);
                i++;
            }
        };

        new Thread(runnable, "Tortoise").start();
        new Thread(runnable, "Rabbit").start();
    }

参考:https://www.cnblogs.com/qdhxhz/p/9393724.html

原文地址:https://www.cnblogs.com/Latiny/p/11389689.html