Java8 Supplier接口和Consumer接口原理解析
Supplier接口
packagejava.util.function; /** *Representsasupplierofresults. * *Thereisnorequirementthatanewordistinctresultbereturnedeach *timethesupplierisinvoked. * *
Thisisa
functionalinterface *whosefunctionalmethodis{@link#get()}. * *@param thetypeofresultssuppliedbythissupplier * *@since1.8 */ @FunctionalInterface publicinterfaceSupplier { /** *Getsaresult. * *@returnaresult */ Tget(); }
supplier接口只有一个抽象方法get(),通过get方法产生一个T类型实例。
实例:
packageme.yanand; importjava.util.function.Supplier; publicclassTestSupplier{ publicstaticvoidmain(String[]args){ SupplierappleSupplier=Apple::new; System.out.println("--------"); appleSupplier.get(); } } classApple{ publicApple(){ System.out.println("创建实例"); } }
Consumer接口
packagejava.util.function; importjava.util.Objects; /** *Representsanoperationthatacceptsasingleinputargumentandreturnsno *result.Unlikemostotherfunctionalinterfaces,{@codeConsumer}isexpected *tooperateviaside-effects. * *Thisisa
functionalinterface *whosefunctionalmethodis{@link#accept(Object)}. * *@param thetypeoftheinputtotheoperation * *@since1.8 */ @FunctionalInterface publicinterfaceConsumer { /** *Performsthisoperationonthegivenargument. * *@paramttheinputargument */ voidaccept(Tt); /** *Returnsacomposed{@codeConsumer}thatperforms,insequence,this *operationfollowedbythe{@codeafter}operation.Ifperformingeither *operationthrowsanexception,itisrelayedtothecallerofthe *composedoperation.Ifperformingthisoperationthrowsanexception, *the{@codeafter}operationwillnotbeperformed. * *@paramaftertheoperationtoperformafterthisoperation *@returnacomposed{@codeConsumer}thatperformsinsequencethis *operationfollowedbythe{@codeafter}operation *@throwsNullPointerExceptionif{@codeafter}isnull */ defaultConsumer andThen(Consumerafter){ Objects.requireNonNull(after); return(Tt)->{accept(t);after.accept(t);}; } }
一个抽象方法accept(Tt)定义了要执行的具体操作;注意看andThen方法,接收Consumer类型参数,返回一个lambda表达式,此表达式定义了新的执行过程,先执行当前Consumer实例的accept方法,再执行入参传进来的Consumer实例的accept方法,这两个accept方法接收都是相同的入参t。
实例:
packageme.yanand; importjava.util.function.Consumer; publicclassTestConsumer{ publicstaticvoidmain(String[]args){ Consumerconsumer=(t)->{ System.out.println(t*3); }; Consumer consumerAfter=(s)->{ System.out.println("之后执行:"+s); }; consumer.andThen(consumerAfter).accept(5); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。