Java Function 介面用法
阿新 • • 發佈:2022-05-08
Java 8 中 Function 介面的介紹
Java 8 中提供了一個函式式介面 Function
,這個介面表示對一個引數做一些操作然後返回操作之後的值。這個介面的有一個抽象方法 apply
,這個方法就是表明對引數做的操作。
// Java Function 介面的定義 @FunctionalInterface public interface Function<T, R> { R apply(T t); default <V> Function<V, R> compose(Function<? super V, ? extends T> before) { Objects.requireNonNull(before); return (V v) -> apply(before.apply(v)); } default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) { Objects.requireNonNull(after); return (T t) -> after.apply(apply(t)); } static <T> Function<T, T> identity() { return t -> t; }
Function 介面的用法
apply
方法的使用方式如下:
Function<Integer, Integer> add = p -> p + 10;
Integer result = add.apply(10);
// 這裡會輸出 20,因為這個函式定義的操作時把引數加上 10 後返回
System.out.println(result);
compose
方法的引數也是一個 Function
物件。在 A 這個 Function
上呼叫 compose
方法時傳入 B 這個 Function
物件,然後得到一個新的 Function
物件 C。C 這個 Function
物件的實現邏輯是先帶哦用 B 的 apply
Function
物件的 apply
方法,然後返回執行後的結果。
addThen
方法也是類似的原理,只不過內部執行方法的順序不一樣而已。
Function<Integer, Integer> multiplyTen = a -> a * 10; Function<Integer, Integer> addTen = a -> a + 10; // 先增加 10,然後再乘 10,輸出結果 110 Function<Integer, Integer> addTenThenMultiplyTen = multiplyTen.compose(addTen); System.out.println(addTenThenMultiplyTen.apply(1)); // 先乘 10,然後再加 10,輸出結果 20 Function<Integer, Integer> multiplyTenAddTenThen = multiplyTen.andThen(addTen); System.out.println(multiplyTenAddTenThen.apply(1));
Function 介面的例項
public class CheckUtils {
private static final Function<String, String> lengthCheck = params -> {
if (params.length() > 100) {
throw new RuntimeException("Length exceed max limit.");
}
return params;
};
private static final Function<String, String> invalidCharacterCheck = str -> {
if (!str.matches("^[a-f,A-F]$")) {
throw new RuntimeException("Contains invalid character.");
}
return str;
};
/**
* 這裡的公共方法組合了該類中的基本校驗邏輯構成一個複合的邏輯
*/
public static void checkStringLengthAndPhoneNumber(String string) {
invalidCharacterCheck.compose(lengthCheck).apply(string);
}
}