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
  • .Net8.0 Blazor Hybird 桌面端 (WPF/Winform) 實測可以完整運行在 win7sp1/win10/win11. 如果用其他工具打包,還可以運行在mac/linux下, 傳送門BlazorHybrid 發佈為無依賴包方式 安裝 WebView2Runtime 1.57 M ...
  • 目錄前言PostgreSql安裝測試額外Nuget安裝Person.cs模擬運行Navicate連postgresql解決方案Garnet為什麼要選擇Garnet而不是RedisRedis不再開源Windows版的Redis是由微軟維護的Windows Redis版本老舊,後續可能不再更新Garne ...
  • C#TMS系統代碼-聯表報表學習 領導被裁了之後很快就有人上任了,幾乎是無縫銜接,很難讓我不想到這早就決定好了。我的職責沒有任何變化。感受下來這個系統封裝程度很高,我只要會調用方法就行。這個系統交付之後不會有太多問題,更多應該是做小需求,有大的開發任務應該也是第二期的事,嗯?怎麼感覺我變成運維了?而 ...
  • 我在隨筆《EAV模型(實體-屬性-值)的設計和低代碼的處理方案(1)》中介紹了一些基本的EAV模型設計知識和基於Winform場景下低代碼(或者說無代碼)的一些實現思路,在本篇隨筆中,我們來分析一下這種針對通用業務,且只需定義就能構建業務模塊存儲和界面的解決方案,其中的數據查詢處理的操作。 ...
  • 對某個遠程伺服器啟用和設置NTP服務(Windows系統) 打開註冊表 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer 將 Enabled 的值設置為 1,這將啟用NTP伺服器功 ...
  • title: Django信號與擴展:深入理解與實踐 date: 2024/5/15 22:40:52 updated: 2024/5/15 22:40:52 categories: 後端開發 tags: Django 信號 松耦合 觀察者 擴展 安全 性能 第一部分:Django信號基礎 Djan ...
  • 使用xadmin2遇到的問題&解決 環境配置: 使用的模塊版本: 關聯的包 Django 3.2.15 mysqlclient 2.2.4 xadmin 2.0.1 django-crispy-forms >= 1.6.0 django-import-export >= 0.5.1 django-r ...
  • 今天我打算整點兒不一樣的內容,通過之前學習的TransformerMap和LazyMap鏈,想搞點不一樣的,所以我關註了另外一條鏈DefaultedMap鏈,主要調用鏈為: 調用鏈詳細描述: ObjectInputStream.readObject() DefaultedMap.readObject ...
  • 後端應用級開發者該如何擁抱 AI GC?就是在這樣的一個大的浪潮下,我們的傳統的應用級開發者。我們該如何選擇職業或者是如何去快速轉型,跟上這樣的一個行業的一個浪潮? 0 AI金字塔模型 越往上它的整個難度就是職業機會也好,或者說是整個的這個運作也好,它的難度會越大,然後越往下機會就會越多,所以這是一 ...
  • @Autowired是Spring框架提供的註解,@Resource是Java EE 5規範提供的註解。 @Autowired預設按照類型自動裝配,而@Resource預設按照名稱自動裝配。 @Autowired支持@Qualifier註解來指定裝配哪一個具有相同類型的bean,而@Resourc... ...