参考: https://blog.csdn.net/boyan_HFUT/article/details/99618833
表示接受一个参数并产生结果的函数。
@FunctionalInterface
public interface Function<T, R> {
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
R apply(T t);
/**
* Returns a composed function that first applies the {@code before}
* function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param the type of input to the {@code before} function, and to the
* composed function
* @param before the function to apply before this function is applied
* @return a composed function that first applies the {@code before}
* function and then applies this function
* @throws NullPointerException if before is null
*
* @see #andThen(Function)
*/
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
/**
* Returns a composed function that first applies this function to
* its input, and then applies the {@code after} function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param the type of output of the {@code after} function, and of the
* composed function
* @param after the function to apply after this function is applied
* @return a composed function that first applies this function and then
* applies the {@code after} function
* @throws NullPointerException if after is null
*
* @see #compose(Function)
*/
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
/**
* Returns a function that always returns its input argument.
*
* @param the type of the input and output objects to the function
* @return a function that always returns its input argument
*/
static <T> Function<T, T> identity() {
return t -> t;
}
}
public class Test {
public static void main(String[] args) throws Exception {
Function<Integer, Integer> add = p -> p + 10;
Integer result = add.apply(10);
// 这里会输出 20,因为这个函数定义的操作时把参数加上 10 后返回
System.out.println(result);
Function<Integer, Integer> multiplyTen = a -> a * 10;
Function<Integer, Integer> addTen = a -> a + 10;
// 先增加 10,然后再乘 10,输出结果 110
Function<Integer, Integer> addTenThenMultiplyTen = multiplyTen.compose(addTen);
System.out.println(addTenThenMultiplyTen.apply(1));
// 先乘 10,然后再加 10,输出结果 20
Function<Integer, Integer> multiplyTenAddTenThen = multiplyTen.andThen(addTen);
System.out.println(multiplyTenAddTenThen.apply(1));
}
}
结果