常用的函数式接口_Function接口_默认方法andThen
生活随笔
收集整理的這篇文章主要介紹了
常用的函数式接口_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> fun1Integer i = fun1.apply("123")+10;第二次是把Integer類型轉換為String類型所以我們可以使用Function<Integer,String> fun2String s = fun2.apply(i);我們可以使用andThen方法,把兩次轉換組合在一起使用String s = fun1.andThen(fun2).apply("123");fun1先調用apply方法,把字符串轉換為Integerfun2再調用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)->{//把字符串轉換為整數+10return Integer.parseInt(str)+10;},(Integer i)->{//把整數轉換為字符串return i+"";});//優化Lambda表達式change(s,str->Integer.parseInt(str)+10,i->i+"");} }第一個操作是將字符串解析成為int數字,第二個操作是乘以10。兩個操作通過andThen 按照前后順序組合到了一起。
請注意,Function的前置條件泛型和后置條件泛型可以相同。
總結
以上是生活随笔為你收集整理的常用的函数式接口_Function接口_默认方法andThen的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 常用的函数式接口_Function接口
- 下一篇: 常用的函数式接口_Function接口练