JDK提供了大量常用的函數式接口以豐富Lambda的典型使用場景,它們主要在 java.util.function 包中被提供。 下面是最簡單的Function接口及使用示例。
Function接口概述
java.util.function.Function<T,R> 接口用來根據一個類型的數據得到另一個類型的數據,前者稱為前置條件,后者稱為后置條件。
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
......
}
抽象方法:apply
Function 接口中最主要的抽象方法為: R apply(T t) ,根據類型T的參數獲取類型R的結果。 使用的場景例如:將 String 類型轉換為 Integer 類型。
import java.util.function.Function;
public class DemoFunctionApply {
public static void main(String[] args) {
method(s -> Integer.parseInt(s));
}
private static void method(Function<String, Integer> function) {
int num = function.apply("10");
System.out.println(num + 20);
}
}
運行程序,控制台輸出:
30
當然,最好是通過方法引用的寫法。
默認方法:andThen
Function 接口中有一個默認的 andThen 方法,用來進行組合操作。JDK源代碼如:
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
該方法同樣用於“先做什么,再做什么”的場景,和 Consumer 中的 andThen 差不多:
import java.util.function.Function;
public class DemoFunctionAndThen {
public static void main(String[] args) {
method(
str -> Integer.parseInt(str)+10,
i -> i *= 10
);
}
private static void method(Function<String, Integer> one, Function<Integer, Integer> two) {
int num = one.andThen(two).apply("10");
System.out.println(num + 20);
}
}
運行程序,控制台輸出:
220
第一個操作是將字符串解析成為int數字,第二個操作是乘以10。兩個操作通過 andThen 按照前后順序組合到了一 起。
請注意,Function的前置條件泛型和后置條件泛型可以相同。
練習:自定義函數模型拼接
題目
請使用 Function 進行函數模型的拼接,按照順序需要執行的多個函數操作為:
String str = "趙麗穎,20";
- 將字符串截取數字年齡部分,得到字符串;
- 將上一步的字符串轉換成為int類型的數字;
- 將上一步的int數字累加100,得到結果int數字。
解答
import java.util.function.Function;
public class DemoFunction {
public static void main(String[] args) {
String str = "趙麗穎,20";
int age = getAgeNum(
str,
s -> s.split(",")[1],
s -> Integer.parseInt(s),
n -> n += 100
);
System.out.println(age);
}
private static int getAgeNum(String str,
Function<String, String> one,
Function<String, Integer> two,
Function<Integer, Integer> three) {
return one.andThen(two).andThen(three).apply(str);
}
}
運行程序,控制台輸出:
120