持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第8天,点击查看活动详情
上一篇文章我们介绍了Consumer接口的使用,这篇文章我们介绍Function接口。
Function 接口
Function 同样也是一个函数式编程接口,从它的名来入手,它的含义是“函数”。
在我们印象中,函数的大概形式为y = f(x),对比这个公式,函数一般来说是有输入输出的,因此它含有一个apply方法,这个方法包含一个输入与一个输出。
除了apply方法,Function接口还有compose、andThen、indentity三个方法,下面我们一一介绍。
首先我们来看Function 接口的函数定义:
@FunctionalInterface
public interface Function<T, R> {
/**
* Applies this function to the given argument.
*/
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.
*/
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.
*/
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.
*/
static <T> Function<T, T> identity() {
return t -> t;
}
}
这里我们仅保留原本的方法介绍。
apply 方法
apply 方法的介绍的中文意思是“将此函数应用于给定的参数”。
输入参数是T,输出参数为R,这个函数很简单的,就是将输入的数据处理一下,然后进行输出。
这个方法比较简单,不做过多介绍。
compose 方法
它的作用是返回一个组合函数,对比代码我们可以发现,该函数首先调用before 的apply 方法,将其返回值作为外面包裹的apply方法的输入,然后返回apply方法的处理结果。
andThen 方法
andThen 的使用方法等同于Consumer 接口的同名方法,先处理自身的apply方法内部逻辑,然后调用传入参数after 的apply 方法,然后再处理本身的apply 方法。
identity 方法
返回一个始终返回其输入参数的Funcion。
使用举例
接下来我们拿例子来看这几个方法的作用。
首先我们定义两个Function:
Function<Integer, Integer> f1 = n -> n + 1;
Function<Integer, Integer> f2 = n -> n * 2;
这个时候,我们执行如下代码:
System.out.println(f1.compose(f2).apply(1));
这段代码的执行顺序是先执行f2 中的apply 函数的逻辑,再执行f1 中apply 方法的逻辑,上面的代码就相当于:
Integer a = f2.apply(1);
System.out.println(f1.apply(a));
最终输出结果是:3
执行如下代码
System.out.println(f1.andThen(f2).apply(1));
这段代码的执行顺序是先执行f1 中的apply 函数的逻辑,再执行f2 中apply 方法的逻辑,上面的代码就相当于:
Integer a = f1.apply(1);
System.out.println(f2.apply(a));
最终返回结果是:4
对于identity 方法,它本是一个静态函数,它会返回一个不进行任何处理的Function,输出与输入值相等。
使用过程可以直接这样用:
System.out.println(Function.identity().apply(1));
输出结果:1
总结
Funciton 接口我们日常开发中使用很多,使用最多的就是apply方法和identity方法。学习这个接口之后,我们一定要在开发中尝试使用,这样才会让知识变成我们的“工具”。