新特性中有個Function接口用在支持lamdba表達式。
個人理解這個接口就是把一些輸入參數封裝在1個 or n個方法內,並且輸出的結果類型可以和參數一致 or 不一致。
同時可以利用這個接口不斷把方法迭代,用來完成方法的組合。
如果大家對於這個類的用法還有其他的想法,歡迎留言。
1. R apply(T t) -> 將function對象應用到輸入的參數上,並且輸出結果
2. default <V> Function<T,V> andThen(Function<? super R, ? extends V> after) -> 先執行Function<T, R>對象的apply(),再執行after的apply(),返回一個新的Function
源碼:
從源碼上可以看出,先執行 Function<T, R> apply(t) = R, 然後再執行Function<R, V> apply(R) = V。 忽略過程,傳入的參數爲T,輸出的結果爲V.
我的理解爲:假設n個andThen()迭代,那麼就是不斷用輸出結果繼續作爲輸入進行操作,最後一個出口的結果作爲最終結果。
2. default <V> Function<V,R>
compose(Function<?
super V,? extends
T> before)
-> 先執行before的apply(),再執行Function<T,R>的apply(),返回一個新的Function
源碼:
從源碼上可以看出,先執行 Function<V, T> apply(v) = T, 然後再執行Function<T, R> apply(T) = R。 忽略過程,初始傳入的參數爲T,輸出的結果爲R.
我的理解爲:假設n個compose()迭代,那麼就是爲了得到R,前面的apply()不斷輸出,直至得到T。4. static <T> Function<T,T>
identity()
-> 返回一個輸入和輸出都爲T的Function對象。
源碼:
例子:
Function<String, Integer> f1 = (t) -> Integer.valueOf(t) * 10;
System.out.println(f1.apply("3"));
System.out.println(Function.identity().apply("3"));
System.out.println(f1.andThen((r) -> String.valueOf(r) + ".....").apply("4"));
System.out.println(f1.compose((String r) -> r.substring(1)).apply("a5"));
輸出爲:
30
3
40.....
50