507
阿裏雲
技術社區[雲棲]
Function接口 – Java8中java.util.function包下的函數式接口
早先我寫了一篇《函數式接口》,探討了Java8中函數式接口的用法。如果你正在瀏覽Java8的API,你會發現java.util.function中 Function, Supplier, Consumer, Predicate和其他函數式接口廣泛用在支持lambda表達式的API中。這些接口有一個抽象方法,會被lambda表達式的定義所覆蓋。在這篇文章中,我會簡單描述Function接口,該接口目前已發布在java.util.function中。
Function接口的主要方法:
R apply(T t) – 將Function對象應用到輸入的參數上,然後返回計算結果。
default ‹V› Function‹T,V› – 將兩個Function整合,並返回一個能夠執行兩個Function對象功能的Function對象。
譯者注:Function接口中除了apply()之外全部接口如下:
default <V> Function<T,V> andThen(Function<? super R,? extends V> after) 返回一個先執行當前函數對象apply方法再執行after函數對象apply方法的函數對象。
default <V> Function<T,V> compose(Function<? super V,? extends T> before)返回一個先執行before函數對象apply方法再執行當前函數對象apply方法的函數對象。
static <T> Function<T,T> identity() 返回一個執行了apply()方法之後隻會返回輸入參數的函數對象。
本章節將會通過創建接受Function接口和參數並調用相應方法的例子探討apply方法的使用。我們同樣能夠看到API的調用者如何利用lambda表達式替代接口的實現。除了傳遞lambda表達式之外,API使用者同樣可以傳遞方法的引用,但這樣的例子不在本篇文章中。
如果你想把接受一些輸入參數並將對輸入參數處理過後的結果返回的功能封裝到一個方法內,Function接口是一個不錯的選擇。輸入的參數類型和輸出的結果類型可以一致或者不一致。
一起來看看接受Function接口實現作為參數的方法的例子:
01 |
public class FunctionDemo {
|
03 |
//API which accepts an implementation of
|
07 |
static void modifyTheValue( int valueToBeOperated, Function<Integer, Integer> function){
|
09 |
int newValue = function.apply(valueToBeOperated);
|
12 |
* Do some operations using the new value.
|
15 |
System.out.println(newValue);
|
下麵是調用上述方法的例子:
01 |
public static void main(String[] args) {
|
03 |
int incr = 20 ; int myNumber = 10 ;
|
05 |
modifyTheValue(myNumber, val-> val + incr);
|
07 |
myNumber = 15 ; modifyTheValue(myNumber, val-> val * 10 );
|
09 |
modifyTheValue(myNumber, val-> val - 100 );
|
11 |
modifyTheValue(myNumber, val-> "somestring" .length() + val - 100 );
|
你可以看到,接受1個參數並返回執行結果的lambda表達式創建在例子中。這個例子的輸入如下:
最後更新:2017-05-23 10:02:23