使用注解 @FunctionalInterface 标识,并且只包含一个 抽象方法 的接口是 函数式接口 1.Function 有参有返回型函数、Function 函数的表现形式为接收一个参数,并返回一个值 2.Consumer 消费型函数、Consumer函数的表现形式为接收一个参数,没有返回值 3.Supplier 供给型函数、表现形式为 不接受参数、只返回数据 4.Runnable 无参无返回型函数、表现形式为无参无返回型函数
例子一:
R apply(T t);
public static int testFunction(int i, Functionfunction) { return function.apply(i); } System.out.println(testFunction(2,i -> i * 2 + 1));
输出结果是 5
例子二:
default Function compose(Function super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
public static int testCompose(int a, FunctionfunA, Function funB) { return funA.compose(funB).apply(a); } System.out.println("compose"+testCompose(5, value -> value - 1,value -> value * 2));
结果:先执行value -> value * 2 >>5*2=10,再执行value -> value - 1, 10-1=9
例子三:
default Function andThen(Function super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
public static int andThen(int a, FunctionfunA, Function funB) { return funA.andThen(funB).apply(a); System.out.println("andThen 结果:"+andThen(5, value -> value - 1,value -> value * 2));
先执行value -> value - 1 >>5-1=4,在执行value -> value * 2 结果是8



