這些JDK8 新特性,我還是第一次聽說

来源:https://www.cnblogs.com/jiagooushi/archive/2023/02/14/17119385.html
-Advertisement-
Play Games

文章內容整理自 博學谷狂野架構師 概述 什麼是函數式介面?簡單來說就是只有一個抽象函數的介面。為了使得函數式介面的定義更加規範,java8 提供了@FunctionalInterface 註解告訴編譯器在編譯器去檢查函數式介面的合法性,以便在編譯器在編譯出錯時給出提示。為了更加規範定義函數介面,給出 ...


文章內容整理自 博學谷狂野架構師

概述

什麼是函數式介面?簡單來說就是只有一個抽象函數的介面。為了使得函數式介面的定義更加規範,java8 提供了@FunctionalInterface 註解告訴編譯器在編譯器去檢查函數式介面的合法性,以便在編譯器在編譯出錯時給出提示。為了更加規範定義函數介面,給出如下函數式介面定義規則:

  • 有且僅有一個抽象函數
  • 必須要有@FunctionalInterface 註解
  • 可以有預設方法

可以看出函數式介面的編寫定義非常簡單,不知道大家有沒有註意到,其實我們經常會用到函數式介面,如Runnable 介面,它就是一個函數式介面:

COPY@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();
}

過去我們會使用匿名內部類來實現線程的執行體:

COPYnew Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello FunctionalInterface");
            }
        }).start();

現在我們使用Lambda 表達式,這裡函數式介面的使用沒有體現函數式編程思想,這裡輸出字元到標準輸出流中,產生了副作用,起到了簡化代碼的作用,當然還有裝B。

COPYnew Thread(()->{
           System.out.println("Hello FunctionalInterface");
       }).start();

Java8 util.function 包下自帶了43個函數式介面,大體分為以下幾類:

  • Consumer 消費介面
  • Function 功能介面
  • Operator 操作介面
  • Predicate 斷言介面
  • Supplier 生產介面

其他介面都是在此基礎上變形定製化罷了。

函數式介面詳細介紹

這裡只介紹最基礎的函數式介面,至於它的變體只要明白了基礎自然就能夠明白

Consumer

消費者介面,就是用來消費數據的。

COPY@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);

    /**
     * Returns a composed {@code Consumer} that performs, in sequence, this
     * operation followed by the {@code after} operation. If performing either
     * operation throws an exception, it is relayed to the caller of the
     * composed operation.  If performing this operation throws an exception,
     * the {@code after} operation will not be performed.
     *
     * @param after the operation to perform after this operation
     * @return a composed {@code Consumer} that performs in sequence this
     * operation followed by the {@code after} operation
     * @throws NullPointerException if {@code after} is null
     */
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}

Consumer 介面中有accept 抽象方法,accept接受一個變數,也就是說你在使用這個函數式介面的時候,給你提供了數據,你只要接收使用就可以了;andThen 是一個預設方法,接受一個Consumer 類型,當你對一個數據使用一次還不夠爽的時候,你還能再使用一次,當然你其實可以爽無數次,只要一直使用andThan方法。

Function

何為Function呢?比如電視機,給你帶來精神上的愉悅,但是它需要用電啊,電視它把電轉換成了你荷爾蒙,這就是Function,簡單電說,Function 提供一種轉換功能。

COPY@FunctionalInterface
public interface Function<T, R> {

    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);

    /**
     * Returns a composed function that first applies the {@code before}
     * function to its input, and then applies this function to the result.
     * If evaluation of either function throws an exception, it is relayed to
     * the caller of the composed function.
     *
     * @param <V> the type of input to the {@code before} function, and to the
     *           composed function
     * @param before the function to apply before this function is applied
     * @return a composed function that first applies the {@code before}
     * function and then applies this function
     * @throws NullPointerException if before is null
     *
     * @see #andThen(Function)
     */
    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }

    /**
     * Returns a composed function that first applies this function to
     * its input, and then applies the {@code after} function to the result.
     * If evaluation of either function throws an exception, it is relayed to
     * the caller of the composed function.
     *
     * @param <V> the type of output of the {@code after} function, and of the
     *           composed function
     * @param after the function to apply after this function is applied
     * @return a composed function that first applies this function and then
     * applies the {@code after} function
     * @throws NullPointerException if after is null
     *
     * @see #compose(Function)
     */
    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }

    /**
     * Returns a function that always returns its input argument.
     *
     * @param <T> the type of the input and output objects to the function
     * @return a function that always returns its input argument
     */
    static <T> Function<T, T> identity() {
        return t -> t;
    }
}

Function 介面 最主要的就是apply 函數,apply 接受T類型數據並返回R類型數據,就是將T類型的數據轉換成R類型的數據,它還提供了compose、andThen、identity 三個預設方法,compose 接受一個Function,andThen也同樣接受一個Function,這裡的andThen 與Consumer 的andThen 類似,在apply之後在apply一遍,compose 則與之相反,在apply之前先apply(這兩個apply具體處理內容一般是不同的),identity 起到了類似海關的作用,外國人想要運貨進來,總得交點稅吧,然後貨物才能安全進入中國市場,當然了想不想收稅還是你說了算的。

Operator

可以簡單理解成算術中的各種運算操作,當然不僅僅是運算這麼簡單,因為它只定義了運算這個定義,但至於運算成什麼樣你說了算。由於沒有最基礎的Operator,這裡將通過 BinaryOperator、IntBinaryOperator來理解Operator 函數式介面,先從簡單的IntBinaryOperator開始。

IntBinaryOperator

從名字可以知道,這是一個二元操作,並且是Int 類型的二元操作,那麼這個介面可以做什麼呢,除了加減乘除,還可以可以實現平方(兩個相同int 數操作起來不就是平方嗎),還是先看看它的定義吧:

@FunctionalInterface
public interface IntBinaryOperator {

    /**
     * Applies this operator to the given operands.
     *
     * @param left the first operand
     * @param right the second operand
     * @return the operator result
     */
    int applyAsInt(int left, int right);
}

IntBinaryOperator 介面內只有一個applyAsInt 方法,其接收兩個int 類型的參數,並返回一個int 類型的結果,其實這個跟Function 介面的apply 有點像,但是這裡限定了,只能是int類型。

BinaryOperator

BinaryOperator 二元操作,看起來它和IntBinaryOperator 是父子關係,實際上這兩者沒有半點關係,但他們在功能上還是有相似之處的:

COPY@FunctionalInterface
public interface BinaryOperator<T> extends BiFunction<T,T,T> {
    /**
     * Returns a {@link BinaryOperator} which returns the lesser of two elements
     * according to the specified {@code Comparator}.
     *
     * @param <T> the type of the input arguments of the comparator
     * @param comparator a {@code Comparator} for comparing the two values
     * @return a {@code BinaryOperator} which returns the lesser of its operands,
     *         according to the supplied {@code Comparator}
     * @throws NullPointerException if the argument is null
     */
    public static <T> BinaryOperator<T> minBy(Comparator<? super T> comparator) {
        Objects.requireNonNull(comparator);
        return (a, b) -> comparator.compare(a, b) <= 0 ? a : b;
    }

    /**
     * Returns a {@link BinaryOperator} which returns the greater of two elements
     * according to the specified {@code Comparator}.
     *
     * @param <T> the type of the input arguments of the comparator
     * @param comparator a {@code Comparator} for comparing the two values
     * @return a {@code BinaryOperator} which returns the greater of its operands,
     *         according to the supplied {@code Comparator}
     * @throws NullPointerException if the argument is null
     */
    public static <T> BinaryOperator<T> maxBy(Comparator<? super T> comparator) {
        Objects.requireNonNull(comparator);
        return (a, b) -> comparator.compare(a, b) >= 0 ? a : b;
    }
}

BinaryOperator 是 BiFunction 生的,而IntBinaryOperator 是從石頭裡蹦出來的,BinaryOperator 自身定義了minBy、maxBy預設方法,並且參數都是Comparator,就是根據傳入的比較器的比較規則找出最小最大的數據。

Predicate

斷言、判斷,對輸入的數據根據某種標準進行評判,最終返回boolean值:

COPY@FunctionalInterface
public interface Predicate<T> {

    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);

    /**
     * Returns a composed predicate that represents a short-circuiting logical
     * AND of this predicate and another.  When evaluating the composed
     * predicate, if this predicate is {@code false}, then the {@code other}
     * predicate is not evaluated.
     *
     * <p>Any exceptions thrown during evaluation of either predicate are relayed
     * to the caller; if evaluation of this predicate throws an exception, the
     * {@code other} predicate will not be evaluated.
     *
     * @param other a predicate that will be logically-ANDed with this
     *              predicate
     * @return a composed predicate that represents the short-circuiting logical
     * AND of this predicate and the {@code other} predicate
     * @throws NullPointerException if other is null
     */
    default Predicate<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }

    /**
     * Returns a predicate that represents the logical negation of this
     * predicate.
     *
     * @return a predicate that represents the logical negation of this
     * predicate
     */
    default Predicate<T> negate() {
        return (t) -> !test(t);
    }

    /**
     * Returns a composed predicate that represents a short-circuiting logical
     * OR of this predicate and another.  When evaluating the composed
     * predicate, if this predicate is {@code true}, then the {@code other}
     * predicate is not evaluated.
     *
     * <p>Any exceptions thrown during evaluation of either predicate are relayed
     * to the caller; if evaluation of this predicate throws an exception, the
     * {@code other} predicate will not be evaluated.
     *
     * @param other a predicate that will be logically-ORed with this
     *              predicate
     * @return a composed predicate that represents the short-circuiting logical
     * OR of this predicate and the {@code other} predicate
     * @throws NullPointerException if other is null
     */
    default Predicate<T> or(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }

    /**
     * Returns a predicate that tests if two arguments are equal according
     * to {@link Objects#equals(Object, Object)}.
     *
     * @param <T> the type of arguments to the predicate
     * @param targetRef the object reference with which to compare for equality,
     *               which may be {@code null}
     * @return a predicate that tests if two arguments are equal according
     * to {@link Objects#equals(Object, Object)}
     */
    static <T> Predicate<T> isEqual(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }
}

Predicate的test 接收T類型的數據,返回 boolean 類型,即對數據進行某種規則的評判,如果符合則返回true,否則返回false;Predicate介面還提供了 and、negate、or,與 取反 或等,isEqual 判斷兩個參數是否相等等預設函數。

Supplier

生產、提供數據:

COPY@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}

非常easy,get方法返回一個T類數據,可以提供重覆的數據,或者隨機種子都可以,就這麼簡單。

函數式介面實戰

Consumer

Consumer 用的太多了,不想說太多,如下:

COPYpublic class Main {
    public static void main(String[] args) {
      Stream.of(1,2,3,4,5,6)
                .forEach(integer -> System.out.println(integer)); //輸出1,2,3,4,5,6
    }
}

這裡使用標準輸出,還是產生了副作用,但是這種程度是可以允許的

Function

轉換,將字元串轉成長度

COPYpublic class Main {
    public static void main(String[] args) {
       Stream.of("hello","FunctionalInterface")
                .map(e->e.length())
                .forEach(System.out::println);
    }
}

運算

COPYpublic class FunctionTest {

    public static void main(String[] args) {

         public static void main(String[] args) {

        Function<Integer, Integer> square = integer -> integer * integer; //定義平方運算

        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);


        list.stream()
                .map(square.andThen(square)) //四次方
                .forEach(System.out::println);

        System.out.println("------");

        list.stream()
                .map(square.compose(e -> e - 1)) //減一再平方
                .forEach(System.out::println);

        System.out.println("------");

        list.stream().map(square.andThen(square.compose(e->e/2))) //先平方然後除2再平方
                .forEach(System.out::println);

    }
}

結果如下

COPY1
16
81
256
------
0
1
4
9
------
0
4
16
64

Operator

BinaryOperator

這裡實現找最大值:

COPYpublic class BinaryOperatorTest {

    public static void main(String[] args) {

        Stream.of(2,4,5,6,7,1)
                .reduce(BinaryOperator.maxBy(Comparator.comparingInt(Integer::intValue))).ifPresent(System.out::println);

    }
}
IntOperator

這裡實現累加功能:

COPYpublic class BinaryOperatorTest {

    public static void main(String[] args) {
        IntBinaryOperator intBinaryOperator = (e1, e2)->e1+e2; //定義求和二元操作
        IntStream.of(2,4,5,6,7,1)
                .reduce(intBinaryOperator).ifPresent(System.out::println);
    }
}

Predicate

篩選出大於0最小的兩個數

COPYpublic class Main {

    public static void main(String[] args) {
        IntStream.of(200,45,89,10,-200,78,94)
                .filter(e->e>0) //過濾小於0的數
                .sorted() //自然順序排序
                .limit(2) //取前兩個
                .forEach(System.out::println);
    }
}

Supplier

這裡一直生產2這個數字,為了能停下來,使用limit

COPYpublic class Main {

    public static void main(String[] args) {
        Stream.generate(()->2)
                .limit(10)
                .forEach(System.out::println);
    }
}

輸出結果

COPY2
2
2
2
2
2
2
2
2
2

總結

Java8的Stream 基本上都是使用util.function包下的函數式介面來實現函數式編程的,而函數式介面也就只分為 Function、Operator、Consumer、Predicate、Supplier 這五大類,只要能理解掌握最基礎的五大類用法,其他變種也能觸類旁通。

本文由傳智教育博學谷狂野架構師教研團隊發佈。

如果本文對您有幫助,歡迎關註點贊;如果您有任何建議也可留言評論私信,您的支持是我堅持創作的動力。

轉載請註明出處!


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

-Advertisement-
Play Games
更多相關文章
  • 教程簡介 轉換率優化定義 - 從定義,基礎知識,瞭解客戶,目標設置,誤區,優化計劃,用戶體驗和漏斗優化,目標網頁優化,降低退回和退出率,測試和優化,測量結果,學習轉換率優化優化技巧,結論。 教程目錄 轉換率優化 - 定義 轉換率優化 - 基礎知識 瞭解您的客戶 轉換率優化 - 目標設定 轉換率優化 ...
  • 前言 由於在2月13日,Autojs的作者發出公告將審查所有代碼,併在最新版刪除了無障礙截圖、通知監聽等功能,在打開所有版本都會提示強制更新,之前關註的公眾號都連夜刪除了教程文章,在搜索時,發現教程作者的文章在其它平臺還未刪除,為了保險起見,備份一下他的文章。由於他寫的文章很多,文章將通過爬蟲的方式 ...
  • 教程簡介 LINQ初學者教程 - 從簡單和簡單的步驟學習LINQ(語言集成查詢),從基本到高級概念,包括概述,環境設置,標準查詢運算符,LINQ to SQL,LINQ對象,LINQ到數據集,LINQ到XML, LINQ to Entities,LINQ Lambda表達式,LINQ with AS ...
  • 1.讓伺服器監聽客戶端的連接請求 1.1 代碼塊 #include <sys/socket.h> #include <netinet/in.h> #include <string.h> #include<stdio.h> #include<stdlib.h> #define BUFFER_LEN 1 ...
  • 大數處理方案 BigInteger 適合保存比較大的整數。 public class BigInteger_ { public static void main(String[] args) { //當我們編程中,需要處理很大的整數,long不夠用 //可以使用BigInteger的類來搞定 // ...
  • Seata是SpringCloud Alibaba開發出的一款開源的分散式事務解決方案,致力於提供高性能和簡單易用的分散式事務服務。Seata 將為用戶提供了 AT 、TCC 、SAGA 和 XA 事務模式,為用戶打造一站式的分散式解決方案。可以很好的解決分散式系統中事務的問題。Seata的主要特點... ...
  • 本文介紹在Anaconda環境中,安裝Python語言pydot與graphviz兩個模塊的方法。 最近進行隨機森林(RF)的樹的可視化操作,需要用到pydot與graphviz模塊;因此記錄一下二者具體的安裝方法。 相關環境的版本信息:Anaconda Navigator:1.10.0;Pytho ...
  • 本篇文章適用於學習過其他面向對象語言(Java、Php),但沒有學過Go語言的初學者。文章主要從Go與Java功能上的對比來闡述Go語言的基礎語法、面向對象編程、併發與錯誤四個方面。 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...