這篇文章主要介紹了Java8中Function接口怎么使用的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇Java8中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;
}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方法對參數進行操作,將得到的結果再作為參數傳遞給 A 這個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));
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);
}
}關于“Java8中Function接口怎么使用”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“Java8中Function接口怎么使用”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。