Function接口之andThen

Function 是一个函数式接口,andThen它的一个默认方法,就是在Function1执行后执行Function2。
源码:

    /**
     * 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));
    }

代码:

        Function<Integer, Integer> first=x ->x*x;
        Function<Integer, Integer> after=y->y*2;
        
        System.out.println(first.apply(3));
        System.out.println(after.apply(3));
        int res=first.andThen(after).apply(4);
        System.out.println(res);

显示结果:

9
6
32

分析:
1.Function1-first 计算一个数的平方,3的平方9
2.Function2-after 计算一个数的2倍,3的两倍6
4.Function1.andThen 先是4的平方16,再16的2倍32.
结论:
f1.andThen(f2).apply(arg) f1执行后,f2执行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值