An interface marked with the annotation @FunctionalInterface and containing only one abstract method is a functional interface
1. Function has parameters and returns functions, and the expression of Function function is to receive a parameter and return a value
2. Consumer consumption function and Consumer function are expressed in the form of receiving a parameter and no return value
3.Supplier is a supply function that does not accept parameters and only returns data
4.Runnable function with no parameters and no return, expressed as a function with no parameters and no return
Example one:
/**
* 将该函数应用到给定的参数
* @param t 函数的参数
* @return 函数的结果
*/
R apply(T t);
public static int testFunction(int i, Function<Integer,Integer> function) {
return function.apply(i);
}
System.out.println(testFunction(2,i -> i * 2 + 1));
The output is 5
Application in production:
Example 2:
/**
* 返回一个组合函数, 首先执行before function的apply方法, 将它的返回作为输入参数再应用当前的function
*/
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
public static int testCompose(int a, Function<Integer, Integer> funA,
Function<Integer, Integer> funB) {
return funA.compose(funB).apply(a);
}
System.out.println("compose"+testCompose(5, value -> value - 1,value -> value * 2));
Result: first execute value -> value * 2 >>5*2=10, then execute value -> value - 1, 10-1=9
Example three:
/**
* 返回一个组合函数, 它是先调用当前函数的apply方法, 再将其结果作为输入参数传递给after function调用apply()
*/
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
public static int andThen(int a, Function<Integer, Integer> funA,
Function<Integer, Integer> funB) {
return funA.andThen(funB).apply(a);
System.out.println("andThen 结果:"+andThen(5, value -> value - 1,value -> value * 2));
First execute value -> value - 1 >>5-1=4, then execute value -> value * 2 and the result is 8