複習Stream流,函數式介面,方法引用

来源:https://www.cnblogs.com/pzistart/archive/2022/12/30/17015819.html
-Advertisement-
Play Games

#增強for迴圈 增強for迴圈 (也稱for each迴圈) 是迭代器遍歷方法的一個“簡化版”,是JDK1.5以後出來的一個高級for迴圈,專門用來遍曆數組和集合。 普通for迴圈 int[] num = {1,2,3,4,5,6}; for(int i = 0 ; i<num.length ; ...


今天對這些內容進行了一個複習,以寫demo加做筆記的形式

stream能夠更加優雅的處理集合、數組等數據,讓我們寫出更加直觀、可讀性更高的數據處理代碼

創建steam流的方式

set、list能夠直接通過.stream()的形式創建steam流
而數組需要通過 Arrays.stream(arr); Stream.of(arr);
map需要通過entrySet()方法,先將map轉換成Set<Map.Entry<String, Integer>> set對象,再通過set.stream()的方式轉換

stream中的api比較多

/**
 * @author Pzi
 * @create 2022-12-30 13:22
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class Test2 {

    @Test
    public void test1() {
        List<Author> authors = S.getAuthors();
        authors
                .stream()
                .distinct()
                .filter(author -> {
                    // 滿足這個條件,那麼才會被篩選到繼續留在stream中
                    return author.getAge() < 18;
                })
                .forEach(author -> System.out.println(author.getAge()));
    }


    // 對雙列集合map的stream操作
    @Test
    public void test2() {
        Map<String, Integer> map = new HashMap<>();
        map.put("蠟筆小新", 19);
        map.put("黑子", 17);
        map.put("日向翔陽", 16);

        //entrySet是一個包含多個Entry的Set數據結構,Entry是key-val型的數據結構
        Set<Map.Entry<String, Integer>> entries = map.entrySet();

        entries.stream()
                .filter(entry -> {
                    return entry.getValue() > 17;
                })
                .forEach(entry -> {
                    System.out.println(entry);
                });
    }


    // stream的map操作,提取stream中對象的屬性,或者計算
    @Test
    public void test3() {
        List<Author> authors = S.getAuthors();
        authors
                .stream()
                .map(author -> author.getName())
                .forEach(name -> System.out.println(name));
        System.out.println(1);

        authors
                .stream()
                .map(author -> author.getAge())
                .map(age -> age + 10)
                .forEach(age -> System.out.println(age));
    }

    // steam的sorted操作
    @Test
    public void test4() {
        List<Author> authors = S.getAuthors();
        authors
                .stream()
                .distinct()
                .sorted(((o1, o2) -> o2.getAge() - o1.getAge()))
                .skip(1)
                .forEach(author -> System.out.println(author.getName() + " " + author.getAge()));
    }

    // flapMap的使用,重新組裝,改變stream流中存放的對象
    @Test
    public void test5() {
        //        列印所有書籍的名字。要求對重覆的元素進行去重。
        List<Author> authors = S.getAuthors();

        authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .distinct()
                .forEach(book -> System.out.println(book.getName()));

        authors.stream()
                // 將以authors為對象的stream流 組裝成 以book為對象的strem流
                .flatMap(author -> author.getBooks().stream())
                .distinct()
                // 將每個book中的category轉換成數組,然後將[x1,x2]代表分類的數組轉換成stream流,然後使用flapMap將該數組stream流組裝成以x1,x2...為對象的stream流
                // 將以book為對象的strem流 組裝成 以category為對象的stream流
                .flatMap(book -> Arrays.stream(book.getCategory().split(",")))
                .distinct()
                .forEach(category -> System.out.println(category));
    }

    // 數組轉換成stream流
    @Test
    public void test6() {
        Integer[] arr = {1, 2, 3, 4, 5};
        Stream<Integer> stream = Arrays.stream(arr);
        stream
                .filter(integer -> integer > 3)
                .forEach(integer -> System.out.println(integer));
    }

    @Test
    public void test7() {
//        列印這些作家的所出書籍的數目,註意刪除重覆元素。
        List<Author> authors = S.getAuthors();
        long count = authors
                .stream()
                .flatMap(author -> author.getBooks().stream())
                .distinct()
                .count();
        System.out.println(count);
    }

    // max() min()
    @Test
    public void test8() {
//	分別獲取這些作家的所出書籍的最高分和最低分並列印。
        List<Author> authors = S.getAuthors();
        Optional<Integer> max = authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .map(book -> book.getScore())
                .max((score1, score2) -> score1 - score2);


        Optional<Integer> min = authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .map(book -> book.getScore())
                .min((score1, score2) -> score1 - score2);
        System.out.println(max.get());
        System.out.println(min.get());

    }

    // stream 的 collect()
    @Test
    public void test9() {
        // 獲取所有作者名字
        List<Author> authors = S.getAuthors();
        Set<String> collect = authors.stream()
                .map(author -> author.getName())
                .collect(Collectors.toSet());
        System.out.println(collect);

        //獲取一個所有書名的Set集合。
        Set<String> collect1 = authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .map(book -> book.getName())
                .collect(Collectors.toSet());
        System.out.println(collect1);

        //	獲取一個Map集合,map的key為作者名,value為List<Book>
        Map<String, List<Book>> collect2 = authors.stream()
                .distinct()
                .collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks()));

        System.out.println(collect2);

    }

    // anyMatch
    @Test
    public void test10() {
        List<Author> authors = S.getAuthors();
        boolean b = authors.stream()
                .anyMatch(author -> author.getAge() > 29);
        System.out.println(b);
    }

    // allMatch
    @Test
    public void test11() {
        List<Author> authors = S.getAuthors();
        boolean b = authors.stream()
                .allMatch(author -> author.getAge() > 18);
        System.out.println(b);
    }

    // findFirst
    @Test
    public void test12() {
        List<Author> authors = S.getAuthors();
        Optional<Author> first = authors.stream()
                .sorted(((o1, o2) -> o1.getAge() - o2.getAge()))
                .findFirst();
        first.ifPresent(author -> System.out.println(author));
    }

    // reduce() 的使用
    @Test
    public void test13() {
        //        使用reduce求所有作者年齡的和
        List<Author> authors = S.getAuthors();
        Integer sum = authors.stream()
                .distinct()
                .map(author -> author.getAge())
                .reduce(0, (result, element) -> result + element);
//                .reduce(0, (result, element) -> result + element);
        System.out.println(sum);
    }

    @Test
    public void test14() {
        //        使用reduce求所有作者中年齡的最小值
        List<Author> authors = S.getAuthors();
        Integer minAge = authors.stream()
                .map(author -> author.getAge())
                .reduce(Integer.MAX_VALUE, (res, ele) -> res > ele ? ele : res);
        System.out.println(minAge);
    }

    // 沒有初始值的reduce()使用
    @Test
    public void test15() {
        List<Author> authors = S.getAuthors();
        Optional<Integer> age = authors.stream()
                .map(author -> author.getAge())
                .reduce((res, ele) -> res > ele ? ele : res);
        System.out.println(age.get());
    }


    // Optional對象的封裝,orElseGet的使用
    @Test
    public void test16() {
        Optional<Author> authorOptional = Optional.ofNullable(null);
        Author author1 = authorOptional.orElseGet(() -> new Author(1l, "1", 1, "1", null));
        System.out.println(author1);
//        authorOptional.ifPresent(author -> System.out.println(author.getName()));
    }

    @Test
    public void test17() {
        Optional<Author> authorOptional = Optional.ofNullable(null);
        try {
            Author author = authorOptional.orElseThrow((Supplier<Throwable>) () -> new RuntimeException("exception"));
            System.out.println(author.getName());
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }

    // Optional的filter()方法
    // ifPresent()可以安全消費Optional中包裝的對象
    @Test
    public void test18() {
        Optional<Author> optionalAuthor = Optional.ofNullable(S.getAuthors().get(0));
        optionalAuthor
                .filter(author -> author.getAge() > 14)
                .ifPresent(author -> System.out.println(author));
    }


    // Optional的isPresent()方法,用來判斷該Optional是否包裝了對象
    @Test
    public void test19() {
        Optional<Author> optionalAuthor = Optional.ofNullable(S.getAuthors().get(0));
        boolean present = optionalAuthor.isPresent();
        if (present) {
            System.out.println(optionalAuthor.get().getName());
        }
    }

    //  Optional的map(),將一個 Optional 轉換成另一個 Optional
    @Test
    public void test20() {
        Optional<Author> optionalAuthor = Optional.ofNullable(S.getAuthors().get(0));
        optionalAuthor.ifPresent(author -> System.out.println(author.getBooks()));
        Optional<List<Book>> books = optionalAuthor.map(author -> author.getBooks());
        books.ifPresent(books1 -> System.out.println(books.get()));
    }

    // 類的靜態方法
    @Test
    public void test21() {
        List<Author> authors = S.getAuthors();
        authors.stream()
                .map(author -> author.getAge())
                .map(integer -> String.valueOf(integer));
        // lambda方法體中只有一行代碼
//                .map(String::valueOf);
    }

    // 對象的實例方法
    @Test
    public void test22() {
        List<Author> authors = S.getAuthors();
        Stream<Author> authorStream = authors.stream();
        StringBuilder sb = new StringBuilder();
        authorStream.map(author -> author.getName())
                // lambda方法體中只有一行代碼,且將參數全部按照順序傳入這個重寫方法中
                .forEach(str -> sb.append(str));
    }


    // 介面中只有一個抽象方法稱為函數式介面
    // 方法引用的條件是:lambda方法體中只有一行方法

    // 構造器的方法引用
    @Test
    public void test23() {
        List<Author> authors = S.getAuthors();
        authors.stream()
                .map(Author::getName)
                .map(StringBuilder::new)
                .map(stringBuilder -> stringBuilder.append("abc"))
                .forEach(System.out::println);
    }


    // steam提供的處理基本數據類型,避免頻繁的自動拆/裝箱,從而達到省時,提高性能
    @Test
    public void test24() {
        List<Author> authors = S.getAuthors();
        authors.stream()
                .map(author -> author.getAge())
                .map(age -> age + 10)
                .filter(age -> age > 18)
                .map(age -> age + 2)
                .forEach(System.out::println);


        authors.stream()
                .mapToInt(author -> author.getAge())
                .map(age -> age + 10)
                .filter(age -> age > 18)
                .map(age -> age + 2)
                .forEach(System.out::println);
    }

    @Test
    public void test25() {
        List<Author> authors = S.getAuthors();
        authors.stream()
                .parallel()
                .map(author -> author.getAge())
                .peek(integer -> System.out.println(integer+" "+Thread.currentThread().getName()))
                .reduce(new BinaryOperator<Integer>() {
                    @Override
                    public Integer apply(Integer result, Integer ele) {
                        return result + ele;
                    }
                }).ifPresent(sum -> System.out.println(sum));
    }


}

lambda表達式

lambda表達式只關心 形參列表 和 方法體
用在重寫抽象方法的時候,一般都是採用lambda表達式的方式來重寫

函數式介面

函數式介面:介面中只有一個抽象方法,就稱之為函數式介面。在Java中Consumer,Funciton,Supplier

方法引用

方法引用:當lambda表達式的方法體中只有一行代碼,並且符合一些規則,就可以將該行代碼轉換成方法引用的形式
可以直接使用idea的提示自動轉換
這隻是一個語法糖,能看懂代碼就行,不要過於糾結


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

-Advertisement-
Play Games
更多相關文章
  • 摘要:MRS IoTDB,它是華為FusionInsight MRS大數據套件中的時序資料庫產品,在深度參與Apache IoTDB社區開源版的基礎上推出的高性能企業級時序資料庫產品。 本文分享自華為雲社區《工業數據分析為什麼要用FusionInsight MRS IoTDB?》,作者:高深廣 。 ...
  • 簡介 CloudCanal 實現了對 Online DDL 工具如 GH-OST 和 PT-OSC 的支持,保證了對端實時同步源端的 Online DDL 操作。 本文以 MySQL -> MySQL 同步鏈路使用 GH-OST 為例,介紹 CloudCanal 是如何支持實時同步 GH-OST 產 ...
  • 統計主題 需求指標【ADS】輸出方式計算來源來源層級 訪客【DWS】pv可視化大屏page_log 直接可求dwd UV(DAU)可視化大屏需要用 page_log 過濾去重dwm UJ 跳出率可視化大屏需要通過 page_log 行為判斷dwm 進入頁面數可視化大屏需要識別開始訪問標識dwd 連續 ...
  • 前言 Angular 按照既定的發版計劃在 11 月中旬發佈了 v15 版本。推遲了一個月(幾乎每個版本都是這個節奏😳),Ng-Matero 也終於更新到了 v15。其實 Ng-Matero 本身的更新非常簡單,但是同步維護的 Material Extensions 這個庫要先於 Ng-Mater ...
  • 談起消息隊列,內心還是會有些波瀾。 消息隊列、緩存、分庫分表是高併發解決方案三劍客,而消息隊列是我最喜歡,也是思考最多的技術。我想按照下麵的四個階段分享我與消息隊列的故事,同時也是對我技術成長經歷的回顧。 ...
  • C語言 我們在學習電腦學科時,往往最先接觸到的編程語言是C,它是所有語言中,最接近底層的高級語言之一,因而它具有執行速度快的優點。但它又具有開發周期長和對於經驗不足的開發者極容易犯錯的缺點。C語言應用範圍廣泛,你幾乎可以在任何場景中看到它的影子。 C語言編譯原理 一個編寫好的C代碼經過編譯成可執行 ...
  • jdk安裝 下載jdk 由於現在主流就是jdk1.8,所以這裡就下載jdk1.8進行演示。官方下載地址:https://www.oracle.com/java/technologies/downloads/#java8-windows。 官方下載需要註冊oracle賬號,國內下載有可能速度慢,若不想 ...
  • 題目來源 400. 第 N 位數字 題目詳情 給你一個整數 n ,請你在無限的整數序列 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...] 中找出並返回第 n 位上的數字。 示例 1: 輸入: n = 3 輸出: 3 示例 2: 輸入: n = 11 輸出: 0 解釋: ...
一周排行
    -Advertisement-
    Play Games
  • 前言 在我們開發過程中基本上不可或缺的用到一些敏感機密數據,比如SQL伺服器的連接串或者是OAuth2的Secret等,這些敏感數據在代碼中是不太安全的,我們不應該在源代碼中存儲密碼和其他的敏感數據,一種推薦的方式是通過Asp.Net Core的機密管理器。 機密管理器 在 ASP.NET Core ...
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 順序棧的介面程式 目錄順序棧的介面程式頭文件創建順序棧入棧出棧利用棧將10進位轉16進位數驗證 頭文件 #include <stdio.h> #include <stdbool.h> #include <stdlib.h> 創建順序棧 // 指的是順序棧中的元素的數據類型,用戶可以根據需要進行修改 ...
  • 前言 整理這個官方翻譯的系列,原因是網上大部分的 tomcat 版本比較舊,此版本為 v11 最新的版本。 開源項目 從零手寫實現 tomcat minicat 別稱【嗅虎】心有猛虎,輕嗅薔薇。 系列文章 web server apache tomcat11-01-官方文檔入門介紹 web serv ...
  • C總結與剖析:關鍵字篇 -- <<C語言深度解剖>> 目錄C總結與剖析:關鍵字篇 -- <<C語言深度解剖>>程式的本質:二進位文件變數1.變數:記憶體上的某個位置開闢的空間2.變數的初始化3.為什麼要有變數4.局部變數與全局變數5.變數的大小由類型決定6.任何一個變數,記憶體賦值都是從低地址開始往高地 ...
  • 如果讓你來做一個有狀態流式應用的故障恢復,你會如何來做呢? 單機和多機會遇到什麼不同的問題? Flink Checkpoint 是做什麼用的?原理是什麼? ...
  • C++ 多級繼承 多級繼承是一種面向對象編程(OOP)特性,允許一個類從多個基類繼承屬性和方法。它使代碼更易於組織和維護,並促進代碼重用。 多級繼承的語法 在 C++ 中,使用 : 符號來指定繼承關係。多級繼承的語法如下: class DerivedClass : public BaseClass1 ...
  • 前言 什麼是SpringCloud? Spring Cloud 是一系列框架的有序集合,它利用 Spring Boot 的開發便利性簡化了分散式系統的開發,比如服務註冊、服務發現、網關、路由、鏈路追蹤等。Spring Cloud 並不是重覆造輪子,而是將市面上開發得比較好的模塊集成進去,進行封裝,從 ...
  • class_template 類模板和函數模板的定義和使用類似,我們已經進行了介紹。有時,有兩個或多個類,其功能是相同的,僅僅是數據類型不同。類模板用於實現類所需數據的類型參數化 template<class NameType, class AgeType> class Person { publi ...
  • 目錄system v IPC簡介共用記憶體需要用到的函數介面shmget函數--獲取對象IDshmat函數--獲得映射空間shmctl函數--釋放資源共用記憶體實現思路註意 system v IPC簡介 消息隊列、共用記憶體和信號量統稱為system v IPC(進程間通信機制),V是羅馬數字5,是UNI ...