注釈 @FunctionalInterface でマークされ、抽象メソッドを 1 つだけ含むインターフェースは、関数型インターフェースです。
1. Function にはパラメータと関数があり、Function 関数の式はパラメータを受け取って値を返すものです。
2. コンシューマ消費関数およびコンシューマ関数はパラメータを受け取る形で表現され、戻り値はありません
3.Supplier はパラメータを受け入れず、データのみを返す供給関数です
4.パラメータもリターンもなしの実行可能な関数。パラメータもリターンもなしの関数として表現されます。
例 1:
/**
* 将该函数应用到给定的参数
* @param t 函数的参数
* @return 函数的结果
*/
R apply(T t);
public static int testFunction(int i, Function<Integer,Integer> function) {
return function.apply(i);
}
System.out.println(testFunction(2,i -> i * 2 + 1));
出力は5です
実稼働環境でのアプリケーション:
例 2:
/**
* 返回一个组合函数, 首先执行before function的apply方法, 将它的返回作为输入参数再应用当前的function
*/
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
public static int testCompose(int a, Function<Integer, Integer> funA,
Function<Integer, Integer> funB) {
return funA.compose(funB).apply(a);
}
System.out.println("compose"+testCompose(5, value -> value - 1,value -> value * 2));
結果: 最初に値 -> 値 * 2 >>5*2=10 を実行し、次に値 -> 値 - 1、10-1=9 を実行します。
例 3:
/**
* 返回一个组合函数, 它是先调用当前函数的apply方法, 再将其结果作为输入参数传递给after function调用apply()
*/
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
public static int andThen(int a, Function<Integer, Integer> funA,
Function<Integer, Integer> funB) {
return funA.andThen(funB).apply(a);
System.out.println("andThen 结果:"+andThen(5, value -> value - 1,value -> value * 2));
最初に value -> value - 1 >>5-1=4 を実行し、次に value -> value * 2 を実行すると、結果は 8 になります。