java8 (jdk 1.8) 新特性——Lambda

来源:https://www.cnblogs.com/zeroll/archive/2022/11/18/16904162.html
-Advertisement-
Play Games

java8 (jdk 1.8) 新特性 ——初步認識 1. 什麼是lambda? 目前已知的是,有個箭頭 -> 說一大段官方話,也沒有任何意義 我們直接看代碼: 之前我們創建線程是這樣的 Runnable runnable = new Runnable() { @Override public vo ...


java8 (jdk 1.8) 新特性 ——初步認識 

 

1. 什麼是lambda?

目前已知的是,有個箭頭  ->  

說一大段官方話,也沒有任何意義

我們直接看代碼:

之前我們創建線程是這樣的

Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("run。。。。。。");
            }
        };
        runnable.run();

用lambda:

    Runnable run2 = () -> System.out.println("run。。。。。。");
        run2.run();

  

 

 

 

是不是感覺特別離譜,看不懂

別急,還有更離譜的

很常見的一個例子,比較兩個整數的大小

之前是這樣寫的

        Comparator<Integer> myCom = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return Integer.compare(o1, o2);
            }
        };

        int compare = myCom.compare(12, 20);
        int compare1 = myCom.compare(20, 12);
        int compare2 = myCom.compare(20, 20);
        System.out.println(compare);
        System.out.println(compare1);
        System.out.println(compare2);
    }

  

用lambda:

        Comparator<Integer> myCom = (o1, o2) -> Integer.compare(o1, o2);

        int compare = myCom.compare(12, 20);
        int compare1 = myCom.compare(20, 12);
        int compare2 = myCom.compare(20, 20);
        System.out.println(compare);
        System.out.println(compare1);
        System.out.println(compare2);

  甚至還可以這樣 (這個是方法引用)

 Comparator<Integer> myCom = Integer::compare;

        int compare = myCom.compare(12, 20);
        int compare1 = myCom.compare(20, 12);
        int compare2 = myCom.compare(20, 20);
        System.out.println(compare);
        System.out.println(compare1);
        System.out.println(compare2);

  

第一個數比第二個數    

大 :返回 1

小:返回 -1

相等:返回 0 

 

 

 

剛接觸是不是黑人問號,這是什麼玩意 

很好,到這,你認識到了lambda 一個缺點,可閱讀性差 ,優點 代碼簡潔

小結:看到 -> lambda           看到 : : 方法引用

 

2.  lamdba 語法

 

 

  • 基本語法 

 1.  箭頭操作符  ->  或者叫做lambda 操作符

 2.  箭頭操作符將lambda 表達式拆分成兩部分 

      左側:Lambda 表達式的參數列表 

      右側:Lambda 表達式中所需執行的功能  , 即 Lambda 體

 

 

3. 語法格式

 

語法格式1:無參數,無返回值 

  •  () -> system.out.println("Hello Lambda")   
    

      

    前邊線程的那個例子就是

 

語法格式2:有一個參數 無返回值

(x)-> System.out.println(x);

  

若只有一個參數可以省略不寫

 

 

 x-> System.out.println(x);

  

 之前的寫法,沒有使用lambda

 Consumer<String> consumer = new Consumer<String>() {
            @Override
            public void accept(String s) {
                System.out.println("輸出的值:"+s);
            }
        };
        
        consumer.accept("今天不想emo了");

  

 使用lambda 

 Consumer<String> consumer = s -> System.out.println("輸出的值:"+s);

        consumer.accept("今天不想emo了");

 

語法格式3:有兩個以上參數 ,並且lambda體有多條語句,有返回值

   Comparator<Integer> myCom = (o1, o2) -> {
            System.out.println("其他語句");
            return Integer.compare(o1, o2);
        };

  

語法格式4  lambda體中只有一條語句,return 和 大括弧都可以省略不寫

Comparator<Integer> com  =(x,y)-> Integer.compare(x,y);

  有沒有發現所有的參數,都沒有參數類型,之前我們寫函數的時候可是要帶上參數類型的

 

語法格式5  lambda表達式參數列表的數據類型可以省略不寫,因為JVM編譯器通過上下文編譯推斷出數據類型——類型推斷 

 

 

 4. 函數式介面

不管上面哪一種語法格式,lambda都是需要函數式介面的支持

 函數式介面:介面中只有一個抽象方法的介面 稱為函數式介面

可以使用一個註解@FunctionalInterface 修飾,可以檢查是否是函數式介面

我們可以看看Runnable  介面 的源碼

完成的介面類代碼如下

 

 

/*
 * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.
 *  ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms
 /

package java.lang;
/**
 * The <code>Runnable</code> interface should be implemented by any
 * class whose instances are intended to be executed by a thread. The
 * class must define a method of no arguments called <code>run</code>.
 * <p>
 * This interface is designed to provide a common protocol for objects that
 * wish to execute code while they are active. For example,
 * <code>Runnable</code> is implemented by class <code>Thread</code>.
 * Being active simply means that a thread has been started and has not
 * yet been stopped.
 * <p>
 * In addition, <code>Runnable</code> provides the means for a class to be
 * active while not subclassing <code>Thread</code>. A class that implements
 * <code>Runnable</code> can run without subclassing <code>Thread</code>
 * by instantiating a <code>Thread</code> instance and passing itself in
 * as the target.  In most cases, the <code>Runnable</code> interface should
 * be used if you are only planning to override the <code>run()</code>
 * method and no other <code>Thread</code> methods.
 * This is important because classes should not be subclassed
 * unless the programmer intends on modifying or enhancing the fundamental
 * behavior of the class.
 *
 * @author  Arthur van Hoff
 * @see     java.lang.Thread
 * @see     java.util.concurrent.Callable
 * @since   JDK1.0
 */
@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

  

 

 

 

 

 

可以看到這裡面就只有一個實現,有一個註解@FunctionalInterface ,說明它就是一個函數式介面,就可以進行lambda簡寫

 

來看 Comparator 也是一樣 有@FunctionalInterface註解

 

 

 

 

 

 

 

 

 

這裡可能就會有疑問,這邊明明是有兩個抽象方法,怎麼是函數式介面呢?

 

別急 !!可以看到這邊的註釋, 說明這個equals 是 重寫了超類 的 equals,本質上是對object 的重寫,官方定義這樣的抽象方法是不會被定義到 抽象介面數的 ,因此實際上只有一個抽象方法

 

 

 

 

 

 我們自己可以試著定義 函數式介面,很簡單

 

 

package com.test1.demo;


@FunctionalInterface
public interface MyFunc {

    void  method();
    
}

  

 

 好了,如果,寫兩個抽象介面會怎樣?

 

 

 

 

 

可以看到註解報錯了,所以註解用來校驗作用就在這

 

 重申一遍,函數式介面:介面中只有一個抽象方法的介面 稱為函數式介面

註解只是拿來校驗的,方便我們一看就知道這是一函數式介面類,不然還得數個數,驗證一下是不是只有一個

 

 現在我也重寫 equals ,可以看到並沒有報錯

 

 

 

 5. java8 中內置四大核心函數式介面 

  •   Consumer<T> 消費型介面 

 //Consumer  消費型介面
    @Test
    public void testConsumer() {
        cosumer(1000, (m) -> System.out.println("星期一" + m)); 
        // 星期一1000.0
    }

    public void cosumer(double m, Consumer<Double> con) {
        con.accept(m);
    }

  

 

  •  供給型介面  supplier<T>

@Test
    public void testSupplier() {
        List<Integer> numList = getNumList(10, () -> (int) (Math.random() * 100));
        for (Integer integer : numList) {
            System.out.println(integer); //100 以內10位隨機整數
        }
    }

    // 需求:產生指定個數的整數放入集合中
    public List<Integer> getNumList(int num, Supplier<Integer> su) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            Integer integer = su.get();
            list.add(integer);
        }
        return list;
    }

  

 

  •  Function<T,R> 函數型介面

 @Test
    public void  FunctioStr(){
        String c = getFunction("sbjikss", str -> str.toUpperCase());
        System.out.println(c); //SBJIKSS
        String sub = getFunction("sbjikss", str -> str.substring(2, 3));
        System.out.println(sub);//j
    }

    public  String  getFunction( String str, Function<String,String> f) {
        return f.apply(str);
    }

  

 

  • 斷言型介面 Predicate<T>  

 public  void  tetPre(){
         List<String> list = Arrays.asList("Hello","sss","xxxx","sjjss");
        List<String> list1 = filterStr(list, (pre) -> pre.length() > 3);
        for (String s : list1) {
            System.out.println(s);  // Hello xxxx  sjjss
        }
    }
   //需求:將滿足條件字元串放入集合中
    public  List<String>  filterStr(List<String> old , Predicate<String> pre ){
        List<String> newList  = new  ArrayList<>();
        for (String str : old) {
            if (pre.test(str)){
               newList.add(str);
            }
        }
        return newList;
    }

  

 感謝閱讀!!!

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 5.6 介面開發-根據文件id打包下載附件 第2-1-2章 傳統方式安裝FastDFS-附FastDFS常用命令 第2-1-3章 docker-compose安裝FastDFS,實現文件存儲服務 第2-1-5章 docker安裝MinIO實現文件存儲服務-springboot整合minio-mini ...
  • web工程路徑 配置tomcat運行快捷鍵 tomcat啟動的預設快捷鍵時shift+f10,可以自定義配置:file-setting-keymap-搜索run,找到右邊寫有shift+f10的選項,右擊選擇add keyboard shortcut 直接按下自定義快捷鍵,會自動識別 如果自定義快捷 ...
  • 同步與非同步 用來表達任務的提交方式 同步: 提交完任務之後原地等待任務的返回結果 期間不做任何事 非同步: 提交完任務之後不願地等待任務的返回結果 直接去做其他事 有結果自動通知 阻塞與非阻塞 用來表達任務的執行狀態 阻塞 程式處於阻塞態 非阻塞 程式處於就緒態、運行態 綜合使用 同步阻塞 提交任務之 ...
  • JSP頁面的基本結構 在傳統的html頁面文件中加入Java程式片和JSP標記就構成了一個JSP頁面,一個JSP頁面可由5種元素構成: 普通的HTML標記和JavaScript標記 JSP標記,如指令標記、動作標記 變數和方法的聲明 Java程式片 Java表達式 執行過程 當Tomcat伺服器上的 ...
  • 🏵️前言 以下我要講解的是Python中一些重要的內置函數,其中比較重要的會詳細講解,比較簡單的會直接結合代碼進行剖析 🍁一、globals()和locals()內置函數 基於字典的形式獲取局部變數和全局變數 globals()——獲取全局變數的字典 locals()——獲取執行本方法所在命名空 ...
  • 本篇文章繼續介紹 Yarn Application 中 ApplicationMaster 部分的編寫方法。 一、Application Master 編寫方法 上一節講了 Client 提交任務給 RM 的全流程,RM 收到任務後,由 ApplicationsManager 向 NM 申請 Con ...
  • 目錄 一.google angle 簡介 1.ANGLE 支持跨平臺 2.ANGLE 支持渲染器 3.ANGLE 下載地址 二.EGL 坐標系 三.猜你喜歡 零基礎 OpenGL ES 學習路線推薦 : OpenGL ES 學習目錄 >> OpenGL ES 基礎 零基礎 OpenGL ES 學習路 ...
  • 在上一篇中通過閱讀Seata服務端的代碼,我們瞭解到TC是如何處理來自客戶端的請求的,今天這一篇一起來瞭解一下客戶端是如何處理TC發過來的請求的。要想搞清楚這一點,還得從GlobalTransactionScanner說起。 啟動的時候,會調用GlobalTransactionScanner#ini ...
一周排行
    -Advertisement-
    Play Games
  • 1、預覽地址:http://139.155.137.144:9012 2、qq群:801913255 一、前言 隨著網路的發展,企業對於信息系統數據的保密工作愈發重視,不同身份、角色對於數據的訪問許可權都應該大相徑庭。 列如 1、不同登錄人員對一個數據列表的可見度是不一樣的,如數據列、數據行、數據按鈕 ...
  • 前言 上一篇文章寫瞭如何使用RabbitMQ做個簡單的發送郵件項目,然後評論也是比較多,也是準備去學習一下如何確保RabbitMQ的消息可靠性,但是由於時間原因,先來說說設計模式中的簡單工廠模式吧! 在瞭解簡單工廠模式之前,我們要知道C#是一款面向對象的高級程式語言。它有3大特性,封裝、繼承、多態。 ...
  • Nodify學習 一:介紹與使用 - 可樂_加冰 - 博客園 (cnblogs.com) Nodify學習 二:添加節點 - 可樂_加冰 - 博客園 (cnblogs.com) 介紹 Nodify是一個WPF基於節點的編輯器控制項,其中包含一系列節點、連接和連接器組件,旨在簡化構建基於節點的工具的過程 ...
  • 創建一個webapi項目做測試使用。 創建新控制器,搭建一個基礎框架,包括獲取當天日期、wiki的請求地址等 創建一個Http請求幫助類以及方法,用於獲取指定URL的信息 使用http請求訪問指定url,先運行一下,看看返回的內容。內容如圖右邊所示,實際上是一個Json數據。我們主要解析 大事記 部 ...
  • 最近在不少自媒體上看到有關.NET與C#的資訊與評價,感覺大家對.NET與C#還是不太瞭解,尤其是對2016年6月發佈的跨平臺.NET Core 1.0,更是知之甚少。在考慮一番之後,還是決定寫點東西總結一下,也回顧一下.NET的發展歷史。 首先,你沒看錯,.NET是跨平臺的,可以在Windows、 ...
  • Nodify學習 一:介紹與使用 - 可樂_加冰 - 博客園 (cnblogs.com) Nodify學習 二:添加節點 - 可樂_加冰 - 博客園 (cnblogs.com) 添加節點(nodes) 通過上一篇我們已經創建好了編輯器實例現在我們為編輯器添加一個節點 添加model和viewmode ...
  • 前言 資料庫併發,數據審計和軟刪除一直是數據持久化方面的經典問題。早些時候,這些工作需要手寫複雜的SQL或者通過存儲過程和觸發器實現。手寫複雜SQL對軟體可維護性構成了相當大的挑戰,隨著SQL字數的變多,用到的嵌套和複雜語法增加,可讀性和可維護性的難度是幾何級暴漲。因此如何在實現功能的同時控制這些S ...
  • 類型檢查和轉換:當你需要檢查對象是否為特定類型,並且希望在同一時間內將其轉換為那個類型時,模式匹配提供了一種更簡潔的方式來完成這一任務,避免了使用傳統的as和is操作符後還需要進行額外的null檢查。 複雜條件邏輯:在處理複雜的條件邏輯時,特別是涉及到多個條件和類型的情況下,使用模式匹配可以使代碼更 ...
  • 在日常開發中,我們經常需要和文件打交道,特別是桌面開發,有時候就會需要載入大批量的文件,而且可能還會存在部分文件缺失的情況,那麼如何才能快速的判斷文件是否存在呢?如果處理不當的,且文件數量比較多的時候,可能會造成卡頓等情況,進而影響程式的使用體驗。今天就以一個簡單的小例子,簡述兩種不同的判斷文件是否... ...
  • 前言 資料庫併發,數據審計和軟刪除一直是數據持久化方面的經典問題。早些時候,這些工作需要手寫複雜的SQL或者通過存儲過程和觸發器實現。手寫複雜SQL對軟體可維護性構成了相當大的挑戰,隨著SQL字數的變多,用到的嵌套和複雜語法增加,可讀性和可維護性的難度是幾何級暴漲。因此如何在實現功能的同時控制這些S ...