lambda

λ表達式本質上是一個匿名方法。讓咱們來看下面這個例子:ide

    public int add(int x, int y) {
        return x + y;
    }函數

轉成λ表達式後是這個樣子:
    
    (int x, int y) -> x + y;線程

參數類型也能夠省略,Java編譯器會根據上下文推斷出來:編譯器

    (x, y) -> x + y; //返回兩數之和
 
或者編譯

    (x, y) -> { return x + y; } //顯式指明返回值class

可見λ表達式有三部分組成:參數列表,箭頭(->),以及一個表達式或語句塊lambda

 

看下面的例子:構造函數

    Thread oldSchool = new Thread( new Runnable () {
        @Override
        public void run() {
            System.out.println("This is from an anonymous class.");
        }
    } );
    
    Thread gaoDuanDaQiShangDangCi = new Thread( () -> {
        System.out.println("This is from an anonymous method (lambda exp).");
    } );方法

注意第二個線程裏的λ表達式,你並不須要顯式地把它轉成一個Runnable,由於Java能根據上下文自動推斷出來:一個Thread的構造函數接受一個Runnable參數,而傳入的λ表達式正好符合其run()函數,因此Java編譯器推斷它爲Runnable。new

相關文章
相關標籤/搜索