Function 提供了一個抽象方法 R apply(T t) 接收一個參數 返回 一個值,還有兩個默認方法和一個靜態方法
compose 是一個嵌套方法,先執行before.apply() 得到運算后的值,再執行apply(),andthen則相反
identity 輸入一個值則返回一個值,t -> t 實際是 apply() 這個方法的實現
另外還有BiFunction、toIntFunction、DoubleToIntFunction 等函數式接口,區別在於參數的不同,比如LongToIntFunction 是接收一個Long參數,返回一個Int值
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; }
方法示例:
arrToArrayList 是在方法體里運算,而 arrToList 則將方法作為參數傳遞進去
package jdk8.function; import java.util.*; import java.util.function.BiFunction; import java.util.function.Function; public class FunctionTest { public static void main(String[] args) { Integer[] i = {1, 2, 4, 5}; Function<Integer[], ArrayList<Integer>> arrayListFunction = FunctionTest::arrToArrayList; arrayListFunction.apply(i).forEach(System.out::println); ArrayList<Integer> list = FunctionTest.arrToList(i, l -> new ArrayList<>(Arrays.asList(l))); list.forEach(System.out::println); FunctionTest.arrToList(i, l -> new HashSet<>(Arrays.asList(l))).forEach(System.out::println); FunctionTest.arrToList(i, l -> new LinkedList<>(Arrays.asList(l))).forEach(System.out::println); FunctionTest.arrToList(i, l -> new LinkedList<>(Arrays.asList(l))).forEach(System.out::println); System.out.println(FunctionTest.compute(7, s -> s + "百")); System.out.println(FunctionTest.addition("hello", "wolrd", (a, b) -> a + " " + b)); Function<String,String> function = Function.identity(); function.apply("hello wolrd"); } //將數組轉為ArrayList
private static <T> ArrayList<T> arrToArrayList(T[] t) { Objects.requireNonNull(t); return new ArrayList<>(Arrays.asList(t)); } private static<T,R> R arrToList(T[] t, Function<T[], R> function) { Objects.requireNonNull(t); return function.apply(t); } public static String compute(int a, Function<Integer, String> function) { return function.apply(a); //function.apply() 接收實際的行為
} public static String addition(String a, String b, BiFunction<String, String, String> biFunction) { return biFunction.apply(a, b); } }