@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 <V> 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 <V> 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 <T> 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;
}
该函数式接口中有四个方法,一个抽象方法,两个默认方法,以及一个静态方法
- R apply(T t);
- default <V> Function<V, R> compose(Function<? super V, ? extends T> before)
- default <V> Function<T, V> andThen(Function<? super R, ? extends V> after)
- static <T> Function<T, T> identity()
针对这四个方法,测试代码如下:
Function<Integer, Integer> times2 = e -> e * 2;
Function<Integer, Integer> squared = e -> e * e;
Integer apply = times2.compose(squared).apply(4);
Integer apply1 = times2.andThen(squared).apply(4);
Integer apply2 = times2.apply(10);
Function<String, String> fun1 = Function.identity();
String str1 = fun1.apply("helloWorld");
System.out.println("apply == " + apply); //apply == 32
System.out.println("apply1 == " + apply1); //apply1 == 64
System.out.println("apply2 == " + apply2); //apply2 == 20
System.out.println(str1); //helloWorld
从测试结果可知:
- apply方法是将入参带入方法中
- compose()括号中的内容在调用函数time2之前运行 4*4=16 16*2 =32
- andThen()括号中的内容在调用函数time2结束之后运行 4*2 =8 8*8=64
- identity() 方法直接返回传入的参数