未公开接口主要指以下哪几类_Java8的 Stream 函数式接口,你了解多少?
點(diǎn)擊藍(lán)色“程序職場(chǎng)”關(guān)注我喲
加個(gè)“星標(biāo)”,天天和你一起進(jìn)步
作者:liteskywww.jianshu.com/p/2338cabc59e1
函數(shù)式接口是伴隨著Stream的誕生而出現(xiàn)的,Java8Stream 作為函數(shù)式編程的一種具體實(shí)現(xiàn),開(kāi)發(fā)者無(wú)需關(guān)注怎么做,只需知道要做什么,各種操作符配合簡(jiǎn)潔明了的函數(shù)式接口給開(kāi)發(fā)者帶來(lái)了簡(jiǎn)單快速處理數(shù)據(jù)的體驗(yàn)。
函數(shù)式接口
什么是函數(shù)式接口?簡(jiǎn)單來(lái)說(shuō)就是只有一個(gè)抽象函數(shù)的接口。為了使得函數(shù)式接口的定義更加規(guī)范,java8 提供了@FunctionalInterface 注解告訴編譯器在編譯器去檢查函數(shù)式接口的合法性,以便在編譯器在編譯出錯(cuò)時(shí)給出提示。為了更加規(guī)范定義函數(shù)接口,給出如下函數(shù)式接口定義規(guī)則:
有且僅有一個(gè)抽象函數(shù)
必須要有@FunctionalInterface 注解
可以有默認(rèn)方法
可以看出函數(shù)式接口的編寫(xiě)定義非常簡(jiǎn)單,不知道大家有沒(méi)有注意到,其實(shí)我們經(jīng)常會(huì)用到函數(shù)式接口,如Runnable 接口,它就是一個(gè)函數(shù)式接口:
@FunctionalInterfacepublic?interface?Runnable?{
????/**
?????*?When?an?object?implementing?interface?Runnable?is?used
?????*?to?create?a?thread,?starting?the?thread?causes?the?object's
?????*?run?method?to?be?called?in?that?separately?executing
?????*?thread.
?????*?
?????*?The?general?contract?of?the?method?run?is?that?it?may
?????*?take?any?action?whatsoever.
?????*
?????*?@see?????java.lang.Thread#run()
?????*/
????public?abstract?void?run();
}
過(guò)去我們會(huì)使用匿名內(nèi)部類來(lái)實(shí)現(xiàn)線程的執(zhí)行體:
new?Thread(new?Runnable()?{????????????@Overridepublic?void?run()?{
????????????????System.out.println("Hello?FunctionalInterface");
????????????}
????????}).start();
現(xiàn)在我們使用Lambda 表達(dá)式,這里函數(shù)式接口的使用沒(méi)有體現(xiàn)函數(shù)式編程思想,這里輸出字符到標(biāo)準(zhǔn)輸出流中,產(chǎn)生了副作用,起到了簡(jiǎn)化代碼的作用,當(dāng)然還有裝B。
?new?Thread(()->{????????????System.out.println("Hello?FunctionalInterface");
????????}).start();
Java8 util.function 包下自帶了43個(gè)函數(shù)式接口,大體分為以下幾類:
Consumer 消費(fèi)接口
Function 功能接口
Operator 操作接口
Predicate 斷言接口
Supplier 生產(chǎn)接口
其他接口都是在此基礎(chǔ)上變形定制化罷了。
函數(shù)式接口詳細(xì)介紹
這里只介紹最基礎(chǔ)的函數(shù)式接口,至于它的變體只要明白了基礎(chǔ)自然就能夠明白。前篇:玩轉(zhuǎn)Java8中的 Stream 之從零認(rèn)識(shí) Stream
Consumer
消費(fèi)者接口,就是用來(lái)消費(fèi)數(shù)據(jù)的。
@FunctionalInterfacepublic?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?andThen(Consumer?super?T>?after)?{
????????Objects.requireNonNull(after);
????????return?(T?t)?->?{?accept(t);?after.accept(t);?};
????}
}
Consumer 接口中有accept 抽象方法,accept接受一個(gè)變量,也就是說(shuō)你在使用這個(gè)函數(shù)式接口的時(shí)候,給你提供了數(shù)據(jù),你只要接收使用就可以了;andThen 是一個(gè)默認(rèn)方法,接受一個(gè)Consumer 類型,當(dāng)你對(duì)一個(gè)數(shù)據(jù)使用一次還不夠爽的時(shí)候,你還能再使用一次,當(dāng)然你其實(shí)可以爽無(wú)數(shù)次,只要一直使用andThan方法。
Function
何為Function呢?比如電視機(jī),給你帶來(lái)精神上的愉悅,但是它需要用電啊,電視它把電轉(zhuǎn)換成了你荷爾蒙,這就是Function,簡(jiǎn)單電說(shuō),Function 提供一種轉(zhuǎn)換功能。
@FunctionalInterfacepublic?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??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??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??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??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??the?type?of?the?input?and?output?objects?to?the?function
?????*?@return?a?function?that?always?returns?its?input?argument
?????*/static??Function<T,?T>?identity()?{return?t?->?t;
????}
}
Function 接口 最主要的就是apply 函數(shù),apply 接受T類型數(shù)據(jù)并返回R類型數(shù)據(jù),就是將T類型的數(shù)據(jù)轉(zhuǎn)換成R類型的數(shù)據(jù),它還提供了compose、andThen、identity 三個(gè)默認(rèn)方法,compose 接受一個(gè)Function,andThen也同樣接受一個(gè)Function,這里的andThen 與Consumer 的andThen 類似,在apply之后在apply一遍,compose 則與之相反,在apply之前先apply(這兩個(gè)apply具體處理內(nèi)容一般是不同的),identity 起到了類似海關(guān)的作用,外國(guó)人想要運(yùn)貨進(jìn)來(lái),總得交點(diǎn)稅吧,然后貨物才能安全進(jìn)入中國(guó)市場(chǎng),當(dāng)然了想不想收稅還是你說(shuō)了算的:。
Operator
可以簡(jiǎn)單理解成算術(shù)中的各種運(yùn)算操作,當(dāng)然不僅僅是運(yùn)算這么簡(jiǎn)單,因?yàn)樗欢x了運(yùn)算這個(gè)定義,但至于運(yùn)算成什么樣你說(shuō)了算。由于沒(méi)有最基礎(chǔ)的Operator,這里將通過(guò) BinaryOperator、IntBinaryOperator來(lái)理解Operator 函數(shù)式接口,先從簡(jiǎn)單的IntBinaryOperator開(kāi)始。
IntBinaryOperator
從名字可以知道,這是一個(gè)二元操作,并且是Int 類型的二元操作,那么這個(gè)接口可以做什么呢,除了加減乘除,還可以可以實(shí)現(xiàn)平方(兩個(gè)相同int 數(shù)操作起來(lái)不就是平方嗎),還是先看看它的定義吧:
@FunctionalInterfacepublic?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 接口內(nèi)只有一個(gè)applyAsInt 方法,其接收兩個(gè)int 類型的參數(shù),并返回一個(gè)int 類型的結(jié)果,其實(shí)這個(gè)跟Function 接口的apply 有點(diǎn)像,但是這里限定了,只能是int類型。
BinaryOperator
BinaryOperator 二元操作,看起來(lái)它和IntBinaryOperator 是父子關(guān)系,實(shí)際上這兩者沒(méi)有半點(diǎn)關(guān)系,但他們?cè)诠δ苌线€是有相似之處的:
@FunctionalInterfacepublic?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??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??BinaryOperator?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??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??BinaryOperator?maxBy(Comparator?super?T>?comparator)?{
????????Objects.requireNonNull(comparator);return?(a,?b)?->?comparator.compare(a,?b)?>=?0???a?:?b;
????}
}
BinaryOperator 是 BiFunction 生的,而IntBinaryOperator 是從石頭里蹦出來(lái)的,BinaryOperator 自身定義了minBy、maxBy默認(rèn)方法,并且參數(shù)都是Comparator,就是根據(jù)傳入的比較器的比較規(guī)則找出最小最大的數(shù)據(jù)。
Predicate
斷言、判斷,對(duì)輸入的數(shù)據(jù)根據(jù)某種標(biāo)準(zhǔn)進(jìn)行評(píng)判,最終返回boolean值:
@FunctionalInterfacepublic?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.
?????*
?????*?
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?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?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.
?????*
?????*?
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
?????*/
????????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??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??Predicate?isEqual(Object?targetRef)?{return?(null?==?targetRef)
??????????????????Objects::isNull
????????????????:?object?->?targetRef.equals(object);
????}
}
Predicate的test 接收T類型的數(shù)據(jù),返回 boolean 類型,即對(duì)數(shù)據(jù)進(jìn)行某種規(guī)則的評(píng)判,如果符合則返回true,否則返回false;Predicate接口還提供了 and、negate、or,與 取反 或等,isEqual 判斷兩個(gè)參數(shù)是否相等等默認(rèn)函數(shù)。
Supplier
生產(chǎn)、提供數(shù)據(jù):
@FunctionalInterfacepublic?interface?Supplier<T>?{
????/**
?????*?Gets?a?result.
?????*
?????*?@return?a?result
?????*/
????T?get();
}
非常easy,get方法返回一個(gè)T類數(shù)據(jù),可以提供重復(fù)的數(shù)據(jù),或者隨機(jī)種子都可以,就這么簡(jiǎn)單。
函數(shù)式接口實(shí)戰(zhàn)
Consumer
Consumer 用的太多了,不想說(shuō)太多,如下:
public?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
????}
}
這里使用標(biāo)準(zhǔn)輸出,還是產(chǎn)生了副作用,但是這種程度是可以允許的
Function
1.轉(zhuǎn)換,將字符串轉(zhuǎn)成長(zhǎng)度
public?class?Main?{????public?static?void?main(String[]?args)?{
???????Stream.of("hello","FunctionalInterface")
????????????????.map(e->e.length())
????????????????.forEach(System.out::println);
????}
}
2.運(yùn)算
public?class?FunctionTest?{????public?static?void?main(String[]?args)?{
?????????public?static?void?main(String[]?args)?{
????????Function<Integer,?Integer>?square?=?integer?->?integer?*?integer;?//定義平方運(yùn)算
????????List?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);
????}
}
結(jié)果如圖:
Operator
1.BinaryOperator
這里實(shí)現(xiàn)找最大值:
public?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);
????}
}
Comparator 后期會(huì)講到
2.IntOperator
這里實(shí)現(xiàn)累加功能:
public?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最小的兩個(gè)數(shù)
public?class?Main?{????public?static?void?main(String[]?args)?{
????????IntStream.of(200,45,89,10,-200,78,94)
????????????????.filter(e->e>0)?//過(guò)濾小于0的數(shù)
????????????????.sorted()?//自然順序排序
????????????????.limit(2)?//取前兩個(gè)
????????????????.forEach(System.out::println);
????}
}
Supplier
這里一直生產(chǎn)2這個(gè)數(shù)字,為了能停下來(lái),使用limit
public?class?Main?{????public?static?void?main(String[]?args)?{
????????Stream.generate(()->2)
????????????????.limit(10)
????????????????.forEach(System.out::println);
????}
}
如圖:
總結(jié)
Java8的Stream 基本上都是使用util.function包下的函數(shù)式接口來(lái)實(shí)現(xiàn)函數(shù)式編程的,而函數(shù)式接口也就只分為 Function、Operator、Consumer、Predicate、Supplier 這五大類,只要能理解掌握最基礎(chǔ)的五大類用法,其他變種也能觸類旁通。
最后祝看完這篇文章的小伙伴收獲滿滿!點(diǎn)個(gè)在看吧~
▎好文推薦
點(diǎn)擊?職場(chǎng)我們?nèi)绾螌ふ易约旱亩ㄎ?職場(chǎng))
點(diǎn)擊?沒(méi)有資源和運(yùn)營(yíng)能力,如何開(kāi)啟副業(yè)之路(副業(yè))
點(diǎn)擊?項(xiàng)目中怎么使用敏捷開(kāi)發(fā)流程(敏捷)
點(diǎn)擊?【程序職場(chǎng)】第一期學(xué)習(xí)資料(java)
▎我的開(kāi)源項(xiàng)目
點(diǎn)擊?一點(diǎn)知識(shí)學(xué)院(Spring boot 開(kāi)源項(xiàng)目)(技能)
點(diǎn)擊?一Eclipse項(xiàng)目如何導(dǎo)入IDEA正常啟動(dòng)(案例:一點(diǎn)知識(shí)學(xué)院)
快加微信(mmlz6879),回復(fù)「程序職場(chǎng)」或右下角點(diǎn)擊「撩我? ?->? 加群」拉你進(jìn)討論群和眾多愛(ài)學(xué)習(xí)的小伙伴一起學(xué)習(xí)。轉(zhuǎn)發(fā)至朋友圈,是對(duì)我最大的支持。總結(jié)
以上是生活随笔為你收集整理的未公开接口主要指以下哪几类_Java8的 Stream 函数式接口,你了解多少?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 全新ryzen1600x处理器,高频内存
- 下一篇: 天启内存条:高性能新选择,游戏爱好者的福