閱讀507 返回首頁    go 阿裏雲 go 技術社區[雲棲]


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 {
02  
03     //API which accepts an implementation of
04  
05     //Function interface
06  
07     static void modifyTheValue(int valueToBeOperated, Function<Integer, Integer> function){
08  
09         int newValue = function.apply(valueToBeOperated);
10  
11         /*     
12          * Do some operations using the new value.     
13          */
14  
15         System.out.println(newValue);
16  
17     }
18  
19 }

下麵是調用上述方法的例子:

01 public static void main(String[] args) {
02  
03     int incr = 20;  int myNumber = 10;
04  
05     modifyTheValue(myNumber, val-> val + incr);
06  
07     myNumber = 15;  modifyTheValue(myNumber, val-> val * 10);
08  
09     modifyTheValue(myNumber, val-> val - 100);
10  
11     modifyTheValue(myNumber, val-> "somestring".length() + val - 100);
12  
13 }

你可以看到,接受1個參數並返回執行結果的lambda表達式創建在例子中。這個例子的輸入如下:

1 30
2  
3 150
4  
5 -85
6  
7 -75

 

最後更新:2017-05-23 10:02:23

  上一篇:go  聊聊我對Java內存模型的理解
  下一篇:go  什麼是上下文切換