Function接口 – Java8中java.util.function包下的函數式接口


java.util.function中 Function, Supplier, Consumer, Predicate和其他函數式接口廣泛用在支持lambda表達式的API中。這些接口有一個抽象方法,會被lambda表達式的定義所覆蓋

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接口實現作為參數的方法的例子:

public class FunctionDemo {
 
    //API which accepts an implementation of
 
    //Function interface
 
    static void modifyTheValue(int valueToBeOperated, Function<Integer, Integer> function){
 
        int newValue = function.apply(valueToBeOperated);
 
        /*    
         * Do some operations using the new value.    
         */
 
        System.out.println(newValue);
 
    }
 
}

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

public static void main(String[] args) {
 
    int incr = 20;  int myNumber = 10;
 
    modifyTheValue(myNumber, val-> val + incr);
 
    myNumber = 15;  modifyTheValue(myNumber, val-> val * 10);
 
    modifyTheValue(myNumber, val-> val - 100);
 
    modifyTheValue(myNumber, val-> "somestring".length() + val - 100);
 
}

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

30
 
150
 
-85
 
-75

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM