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
  • Timer是什麼 Timer 是一種用於創建定期粒度行為的機制。 與標準的 .NET System.Threading.Timer 類相似,Orleans 的 Timer 允許在一段時間後執行特定的操作,或者在特定的時間間隔內重覆執行操作。 它在分散式系統中具有重要作用,特別是在處理需要周期性執行的 ...
  • 前言 相信很多做WPF開發的小伙伴都遇到過表格類的需求,雖然現有的Grid控制項也能實現,但是使用起來的體驗感並不好,比如要實現一個Excel中的表格效果,估計你能想到的第一個方法就是套Border控制項,用這種方法你需要控制每個Border的邊框,並且在一堆Bordr中找到Grid.Row,Grid. ...
  • .NET C#程式啟動閃退,目錄導致的問題 這是第2次踩這個坑了,很小的編程細節,容易忽略,所以寫個博客,分享給大家。 1.第一次坑:是windows 系統把程式運行成服務,找不到配置文件,原因是以服務運行它的工作目錄是在C:\Windows\System32 2.本次坑:WPF桌面程式通過註冊表設 ...
  • 在分散式系統中,數據的持久化是至關重要的一環。 Orleans 7 引入了強大的持久化功能,使得在分散式環境下管理數據變得更加輕鬆和可靠。 本文將介紹什麼是 Orleans 7 的持久化,如何設置它以及相應的代碼示例。 什麼是 Orleans 7 的持久化? Orleans 7 的持久化是指將 Or ...
  • 前言 .NET Feature Management 是一個用於管理應用程式功能的庫,它可以幫助開發人員在應用程式中輕鬆地添加、移除和管理功能。使用 Feature Management,開發人員可以根據不同用戶、環境或其他條件來動態地控制應用程式中的功能。這使得開發人員可以更靈活地管理應用程式的功 ...
  • 在 WPF 應用程式中,拖放操作是實現用戶交互的重要組成部分。通過拖放操作,用戶可以輕鬆地將數據從一個位置移動到另一個位置,或者將控制項從一個容器移動到另一個容器。然而,WPF 中預設的拖放操作可能並不是那麼好用。為瞭解決這個問題,我們可以自定義一個 Panel 來實現更簡單的拖拽操作。 自定義 Pa ...
  • 在實際使用中,由於涉及到不同編程語言之間互相調用,導致C++ 中的OpenCV與C#中的OpenCvSharp 圖像數據在不同編程語言之間難以有效傳遞。在本文中我們將結合OpenCvSharp源碼實現原理,探究兩種數據之間的通信方式。 ...
  • 一、前言 這是一篇搭建許可權管理系統的系列文章。 隨著網路的發展,信息安全對應任何企業來說都越發的重要,而本系列文章將和大家一起一步一步搭建一個全新的許可權管理系統。 說明:由於搭建一個全新的項目過於繁瑣,所有作者將挑選核心代碼和核心思路進行分享。 二、技術選擇 三、開始設計 1、自主搭建vue前端和. ...
  • Csharper中的表達式樹 這節課來瞭解一下表示式樹是什麼? 在C#中,表達式樹是一種數據結構,它可以表示一些代碼塊,如Lambda表達式或查詢表達式。表達式樹使你能夠查看和操作數據,就像你可以查看和操作代碼一樣。它們通常用於創建動態查詢和解析表達式。 一、認識表達式樹 為什麼要這樣說?它和委托有 ...
  • 在使用Django等框架來操作MySQL時,實際上底層還是通過Python來操作的,首先需要安裝一個驅動程式,在Python3中,驅動程式有多種選擇,比如有pymysql以及mysqlclient等。使用pip命令安裝mysqlclient失敗應如何解決? 安裝的python版本說明 機器同時安裝了 ...