前面介绍了函数式接口Predicate和Consumer,本文继续介绍另一函数式接口Function<T, R>,此接口同样也位于 java.util.function包中,它的作用可以看作是消费者和生产者的结合,即消费某种原材料然后生产出某种产品,继续先分析一下源码。
源码解析
package java.util.function;
import java.util.Objects;
/**
* Represents a function that accepts one argument and produces a result.
* 此接口中的方法接收一个参数并输出一个结果
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #apply(Object)}.
*
* @param <T> the type of the input to the function
* @param <R> the type of the result of the function
*
* @since 1.8
*/
@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.
* 此方法将两个function进行组合,得到一个新的function,组合的过程中如果有一个function出现了异常,异常由调用者来处理。组合逻辑是,将其中一个function以参数的形式传入(before),在compose内部获取before的结果,并传给第二个function组成一个新的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
* 这句话好难理解,简单来就说就是将一个function当作一个参数
* @return a composed function that first applies the {@code before}
* function and then applies this function
* 将before function的结果传给当前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.
*此函数和compose函数有点类似,但顺序不同。此函数是先执行调用者,再执行andThen的参数,即将调用者的结果传给参数中的function使用,并返回一个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

最低0.47元/天 解锁文章
-常见函数式接口- Function<T, R>&spm=1001.2101.3001.5002&articleId=124861610&d=1&t=3&u=04ed7dfba9aa49d28b4268a657b69472)

被折叠的 条评论
为什么被折叠?



