學習java核心技術卷之lambda隨筆

來源:互聯網
上載者:User

標籤:標記   string   new   構造器   this   AC   compare   time   核心   

Lambda運算式

  形式:參數,箭頭(->),運算式

    參數類型要寫,如果可以推匯出來則可以不寫

    只有一個參數可以省略小括弧

    無參數要寫空括弧()

    *如果分支傳回值,那麼所有分支都要傳回值,否則不合法

   函數式介面:只有一個抽象方法的介面(可以用@FunctionalInterface註解標記)

    比如,javax.swing.Timer中可以這樣

      Timer t = new Timer(1000, event ->

      {

        …

      });

    這個構造器的第二個參數需要一個ActionListener執行個體,ActionListener

    就是只有一個方法的介面,所以可以使用 lambda運算式。

  方法引用

    Object::instanceMethod

    Class::staticMethod

    Class::instanceMethod

    如:event -> System.out.println(event)  等價於 System.out :: println

      Math::pow  等價於 (x, y) -> Math.pow(x, y)

    而第三種情況,第一個參數會成為方法的目標如 :String::compareToIgnoreCase 等價於(x,y) -> x.compareToIgnoreCase(y)

    還有可以使用this和super參數;

    Super :: instanceMethod

  構造器引用:

    X -> new int[x] 等價於 int[]::new

    Person x = New Person(…) 等價於 Person::new

    當有多個構造器時,編譯器會從上下文推導

學習java核心技術卷之lambda隨筆

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.