常用的函數式接口_Function接口_默認方法andThen

默認方法:andThen

Function 接口中有一個默認的andThen 方法,用來進行組合操作。JDK源代碼如:

default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
    Objects.requireNonNull(after);
    return (T t) ‐> after.apply(apply(t));
}

該方法同樣用於“先做什麼,再做什麼”的場景,和Consumer 中的andThen 差不多:

package com.learn.demo07.Function;

import java.util.function.Function;

/*
    Function接口中的默認方法andThen:用來進行組合操作

    需求:
        把String類型的"123",轉換爲Inteter類型,把轉換後的結果加10
        把增加之後的Integer類型的數據,轉換爲String類型

    分析:
        轉換了兩次
        第一次是把String類型轉換爲了Integer類型
            所以我們可以使用Function<String,Integer> fun1
                Integer i = fun1.apply("123")+10;
        第二次是把Integer類型轉換爲String類型
            所以我們可以使用Function<Integer,String> fun2
                String s = fun2.apply(i);
        我們可以使用andThen方法,把兩次轉換組合在一起使用
            String s = fun1.andThen(fun2).apply("123");
            fun1先調用apply方法,把字符串轉換爲Integer
            fun2再調用apply方法,把Integer轉換爲字符串
 */
public class Demo02Function_andThen {
    /*
        定義一個方法
        參數串一個字符串類型的整數
        參數再傳遞兩個Function接口
            一個泛型使用Function<String,Integer>
            一個泛型使用Function<Integer,String>
     */
    public static void change(String s, Function<String,Integer> fun1,Function<Integer,String> fun2){
        String ss = fun1.andThen(fun2).apply(s);
        System.out.println(ss);
    }

    public static void main(String[] args) {
        //定義一個字符串類型的整數
        String s = "123";
        //調用change方法,傳遞字符串和兩個Lambda表達式
        change(s,(String str)->{
            //把字符串轉換爲整數+10
            return Integer.parseInt(str)+10;
        },(Integer i)->{
            //把整數轉換爲字符串
            return i+"";
        });

        //優化Lambda表達式
        change(s,str->Integer.parseInt(str)+10,i->i+"");
    }
}

第一個操作是將字符串解析成爲int數字,第二個操作是乘以10。兩個操作通過andThen 按照前後順序組合到了一起。

請注意,Function的前置條件泛型和後置條件泛型可以相同。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章