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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM