高阶函数:如果一个函数接收一个函数作为参数,或者返回一个函数作为返回值,那么该函数就叫做高阶函数。
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,接收一个参数,同时会返回一个参数:
public class MyTest4 { public static void main(String[] args) { MyTest4 test4 = new MyTest4(); //下面几种调用operate的形式使用Function函数式接口实现,传递的是行为,如果采用传统的方式,则下面几种不同的操作必须定义不同的方法才能够实现 //减少方法的定义,重用性更好 test4.operate(1,value -> {return value + 1;}); test4.operate(2,value -> value * value); test4.operate(3,value -> value - 1); } public int operate(int a, Function<Integer,Integer> function){ return function.apply(a); } }compose和andThen函数的应用:
public class MyTest5 { public static void main(String[] args) { MyTest5 test5 = new MyTest5(); //输出12,compose函数是先将输入参数传递func2中的apply方法,返回值作为func1的参数,然后执行func1的apply方法 System.out.println(test5.oper1(2,value -> value * 3,value -> value * value)); //输出36,andThen方法是将输入参数传递给当前调用Function,当前调用的Function是func1,执行完后将返回值作为func2的参数传入,并执行func2的apply方法 System.out.println(test5.oper2(2,value -> value * 3,value -> value * value)); } public int oper1(int a, Function<Integer,Integer> func1,Function<Integer,Integer> func2){ return func1.compose(func2).apply(a); } public int oper2(int a, Function<Integer,Integer> func1,Function<Integer,Integer> func2){ return func1.andThen(func2).apply(a); } }BiFunction函数式接口,是Function函数式接口的一种变体,接收两个参数,返回一个值;可以看到BIFunction中只有andThen方法,而没有compose方法,如果提供compose方法,则compose方法中的参数一定是BIFunction类型,因为传入的是两个参数,但是BIFunction执行apply方法之后只返回一个参数,那么compose方法中执行完before中的apply之后,无法再执行调用的BiFunction中的apply方法,因为此时参数只有一个了。