JAVA8新特性——Lamda表達式


  JAVA9都要出來了,JAVA8新特性都沒搞清楚,是不是有點掉隊哦~

  Lamda表達式,讀作λ表達式,它實質屬於函數式編程的概念,要理解函數式編程的產生目的,就要先理解匿名內部類。

  先來看看傳統的匿名內部類調用方式:

interface MyInterface{

    void lMethod();
}
public class Main {

    public static void test(MyInterface myInterface){
        myInterface.lMethod();
    }

    public static void main(String[] args) {
        test(new MyInterface() {
            @Override
            public void lMethod() {
                System.out.println("Hello World!");
            }
        });
    }
}

  在主類中的這么幾行代碼,嵌套幾層就為了輸出一個Hello World!是不是很麻煩?但是由於java結構的完整性,我們還不得不那么做,現在JDK1.8來了。

  再來看看使用Lamda表達式改寫上面的代碼:

interface MyInterface{

    void lMethod();
}
public class Main {

    public static void test(MyInterface myInterface){
        myInterface.lMethod();
    }

    public static void main(String[] args) {
        test(()->System.out.println("Hello World!"));
    }
}

  這就是Lamda表達式語言,為了解決匿名內部類繁雜的操作而出現。

Lamda語法有三種形式:

  • (參數) ->單行語句;
  • (參數) ->{多行語句};
  • (參數) ->表達式;

  括號()可以大致理解為就是方法,里面是參數變量,在上面的例子中()->System.out.println("Hello World!") 前面的()代表void lMethod()方法,它沒有入參,所以為空,->后面是一個單行語句;

  如果->后面是多行語句,需要用{ }裝起來,每條語句后需要有分號;

  ->后面也可以是一個表達式,如:a+b等。

(參數) ->單行語句:

interface MyInterface{

    void lMethod(String str);
}
public class Main {

    public static void test(MyInterface myInterface){
        myInterface.lMethod("Hello World!");//設置參數內容
    }

    public static void main(String[] args) {
        //首先在()中定義此表達式里面需要接收變量s,后面的單行語句中就可以使用該變量了
        test((s)->System.out.println(s));
    }
}

(參數) ->{多行語句}:

interface MyInterface{

    void lMethod(String str);
}
public class Main {

    public static void test(MyInterface myInterface){
        myInterface.lMethod("Hello World!");//設置參數內容
    }

    public static void main(String[] args) {
        //首先在()中定義此表達式里面需要接收變量s,后面的多行語句中就可以使用該變量了。注意:多行語句別少“;”號
        test((s)->{
            s=s+s;
            System.out.println(s);
        });
    }
}

(參數) ->表達式:

interface MyInterface{

    int lMethod(int a,int b);
}
public class Main {

    public static void test(MyInterface myInterface){
        int result=myInterface.lMethod(1,2);//設置參數內容,接收返回參數
        System.out.println(result);
    }
    public static void main(String[] args) {

        test((x,y)-> x*y );//調用方法
        //相當於
//        test((x,y)-> {return  x*y;});
    }
}

  這樣,Lamda表達式就看起來很簡單了,有不有!

  匿名內部類,我們比較常用的地方在哪兒?線程類Thread,以前我們可能這樣寫:

new Thread(new Runnable() {
@Override
public void run() {
System.out.println("線程操作!");
}
});

  現在,使用Lamda表達式,簡單寫為:

new Thread(()->System.out.println("線程操作!"));

  

  總結:利用Lamda表達式是為了避免匿名內部類定義過多無用的操作。

 

  


免責聲明!

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



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