官方解释:
一个函数式接口,函数方法为 apply(Object);
接受一个参数,返回一个接口;
@FunctionalInterfacepublic interface Function<T, R> {// 待实现的 函数式 接口R apply(T t);// 将两个函数式接口拼接在一起,第1个方法的结果作为 第二个方法的参数default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {Objects.requireNonNull(before);return (V v) -> apply(before.apply(v));}// 将两个函数式接口拼接在一起,第1个方法的结果作为 第二个方法的参数 【与上一个行为相反,参见下面case】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 demo*/public class FunctionTest {public static int compute(int a, Function<Integer, Integer> function) {return function.apply(a);}public static int composeCompute(int a, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {return function1.compose(function2).apply(a);}public static int andThenCompute(int a,Function<Integer,Integer> function1,Function<Integer,Integer> function2){return function1.andThen(function2).apply(a);}public static int biCompute(int a,int b, BiFunction<Integer,Integer,Integer> function){return function.apply(a,b);}public static void main(String[] args) {// int result = compute(1, value -> value + 1);// int result = composeCompute(1,value -> value + 1,value -> value * 2);// int result = andThenCompute(1,value -> value + 1,value -> value * 2);int result = biCompute(1,2, Integer::sum);System.out.println("-------> " + result);}}
