一個Java 8中簡單Lambda表達式程序

ydn7 9年前發布 | 19K 次閱讀 Java 8 Java開發

原文鏈接 作者: Mohamed Sanaulla 譯者: 李璟(jlee381344197@gmail.com)

我嘗試過把Lambda表達式融入到我的代碼中,下面的代碼例子是此次嘗試的結果。對于那些完全不知道Lambda表達式的Java程序員,我強烈建議在繼續閱讀之前,瀏覽一下這篇文章

Ok,現在你已經熟悉Lambda表達式了(在閱讀過推薦的Lambda入門文章之后),那我們現在開始學習一個我認為很好的Lambda表達式的例子。

考慮一下這種場景:某些操作在執行之前需要做預處理,執行之后需要做后期處理。待執行的操作會隨著行為的不同而變化。預處理會提取出這個操作所需的必要參數,后期處理做一些清理的工作。

我們來看看如何利用接口與接口的匿名實現類模擬這個場景。

使用匿名內部類

一個提供了必要行為方法的接口實現:

interface OldPerformer {

    public void performTask(String id, int status);

}

接下來是一些預處理和后期處理方法:

public class PrePostDemo {

    static void performTask(String id, OldPerformer performer) {

        System.out.println("Pre-Processing...");

        System.out.println("Fetching the status for id: " + id);

        int status = 3;

        //Some status value fetched

        performer.performTask(id, status);

        System.out.println("Post-processing...");

    }

}

我們需要傳遞2樣東西:預處理所需的標識,以及操作的實現。如下所示:

public class PrePostDemo {

    public static void main(String[] args) {

    //has to be declared final to be accessed within

    //the anonymous inner class.

    final String outsideOfImpl = "Common Value";

    performTask("1234", new OldPerformer() {

        @Override

        public void performTask(String id, int status) {

            System.out.println("Finding data based on id..."

        );

            System.out.println(outsideOfImpl);

            System.out.println("Asserting that the status matches");

        }

    });

    performTask("4567", new OldPerformer() {

        @Override

        public void performTask(String id, int status) {

            System.out.println("Finding data based on id...");

            System.out.println(outsideOfImpl);

            System.out.println("Update status of the data found");

        }

    });

    }

}

從上面的代碼可以看出,匿名內部類外部的變量要想被匿名內部類訪問,需要聲明成final。例子的代碼輸出如下:

Pre-Processing...</pre>
Fetching the status for id: 1234

Finding data based on id...

Common Value

Asserting that the status matches

Post-processing...

PreProcessing...

Fetching the status for id: 4567

Finding data based on id...

Common Value

Update the status of the data found

Post-processing...

使用Lambda表達式

我們來看看如何用Lambda表達式實現上述例子:

public class PrePostLambdaDemo {

    public static void main(String[] args) {

        //Need not be declared as final for use within a

        //lambda expression, but has to be eventually final.

        String outsideOfImpl = "Common Value";

        doSomeProcessing("123", (String id, int status) -> {

            System.out.println("Finding some data based on"+id);

            System.out.println(outsideOfImpl);

            System.out.println("Assert that the status is "+status );

        });

        doSomeProcessing("456", (String id, int status) -> {

            System.out.print("Finding data based on id: "+id);

            System.out.println(outsideOfImpl);

            System.out.println("And updating the status: "+status);

        });

    }

    static void doSomeProcessing(String id, Performer performer ){

        System.out.println("Pre-Processing...");

        System.out.println("Finding status for given id: "+id);

        int status = 2;

        performer.performTask(id, status);

        System.out.println("Post-processing...");

    }

}

interface Performer{

    public void performTask(String id, int status);

}

除了有趣的Lambda表達式語法之外,還有一點不同,那就是Lambda表達式外部的變量沒有聲明成final。但最終變量還是會成為常量,這意味著outsideOfImpl 在聲明及初始化之后的值不能被更改。

這個例子只是展示了如何使用清晰明了的Lambda表達式代替匿名內部類。

一個小提示:JDK8的發布時間推遲到了2014年2月,完整的發布時間表可以從這里查閱。我每天都會更新Lambda的構建項目,如果在最新的構建中出現了任何問題,請隨時聯系我。我會盡最大努力持續構建,并且會在這里發表最新的例子。

另一個提示:不要讓Java 8的更新使你不知所措,大部分新特性已經存在于其他編程語言中。我發現學習Lambda表達式的語法和方法可以幫助我以函數式的思維進行思考,對此我還應特別感謝Scala閉包。

 本文由用戶 ydn7 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!