常用的函数式接口_Consumer接口的默认方法andThen
生活随笔
收集整理的這篇文章主要介紹了
常用的函数式接口_Consumer接口的默认方法andThen
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
默認(rèn)方法:andThen
如果一個(gè)方法的參數(shù)和返回值全都是Consumer 類型,那么就可以實(shí)現(xiàn)效果:消費(fèi)數(shù)據(jù)的時(shí)候,首先做一個(gè)操作,然后再做一個(gè)操作,實(shí)現(xiàn)組合。而這個(gè)方法就是Consumer 接口中的default方法andThen 。下面是JDK的源代碼:
default Consumer<T> andThen(Consumer<? super T> after) {Objects.requireNonNull(after);return (T t) ‐> { accept(t); after.accept(t); }; }備注: java.util.Objects 的requireNonNull 靜態(tài)方法將會(huì)在參數(shù)為null時(shí)主動(dòng)拋出NullPointerException 異常。這省去了重復(fù)編寫if語句和拋出空指針異常的麻煩。
要想實(shí)現(xiàn)組合,需要兩個(gè)或多個(gè)Lambda表達(dá)式即可,而andThen 的語義正是“一步接一步”操作。例如兩個(gè)步驟組合的情況:
package com.learn.demo05.Consumer;import java.util.function.Consumer;/*Consumer接口的默認(rèn)方法andThen作用:需要兩個(gè)Consumer接口,可以把兩個(gè)Consumer接口組合到一起,在對(duì)數(shù)據(jù)進(jìn)行消費(fèi)例如:Consumer<String> con1Consumer<String> con2String s = "hello";con1.accept(s);con2.accept(s);連接兩個(gè)Consumer接口 再進(jìn)行消費(fèi)con1.andThen(con2).accept(s); 誰寫前邊誰先消費(fèi) */ public class Demo02AndThen {//定義一個(gè)方法,方法的參數(shù)傳遞一個(gè)字符串和兩個(gè)Consumer接口,Consumer接口的泛型使用字符串public static void method(String s, Consumer<String> con1 ,Consumer<String> con2){//con1.accept(s);//con2.accept(s);//使用andThen方法,把兩個(gè)Consumer接口連接到一起,在消費(fèi)數(shù)據(jù)con1.andThen(con2).accept(s);//con1連接con2,先執(zhí)行con1消費(fèi)數(shù)據(jù),在執(zhí)行con2消費(fèi)數(shù)據(jù)}public static void main(String[] args) {//調(diào)用method方法,傳遞一個(gè)字符串,兩個(gè)Lambda表達(dá)式method("Hello",(t)->{//消費(fèi)方式:把字符串轉(zhuǎn)換為大寫輸出System.out.println(t.toUpperCase());},(t)->{//消費(fèi)方式:把字符串轉(zhuǎn)換為小寫輸出System.out.println(t.toLowerCase());});} }?
總結(jié)
以上是生活随笔為你收集整理的常用的函数式接口_Consumer接口的默认方法andThen的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 常用的函数式接口_Consumer接口
- 下一篇: 常用的函数式接口_Consumer接口练