操作接口Function和Consumer

Function接口的源码

@FunctionalInterface
public interface Function<T, R> {
/**
     * 将参数赋予给相应方法
     * 
     * @param t
     * @return
     */
 
    R apply(T t);
/**
     * 先执行参数(即也是一个Function)的,再执行调用者(同样是一个Function)
     */
 
    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
       //判定不能为空
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }
 /**
     * 先执行调用者,再执行参数,和compose相反。
     */

    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
    
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }

 /**
     * 返回当前正在执行的方法
     */
    static <T> Function<T, T> identity() {
        return t -> t;
    }
}

下面的方法比较简单,就是对于接口中apply方法的应用。
通过调用顺序来进行操作。

具体例子

public class testFunction {
    public static void main(String[] args) {
        Function<Integer,Integer>time=i->i*2;
        Function<Integer,Integer>square=i->i*i;

        System.out.println(time.apply(2));
        System.out.println(square.apply(3));

        /**
         * 注意andThen和compose只对当前后面的一个操作有效,
         * 因为链式调用可以长链,读者不要误淆。
         */
        //先执行apply再执行andthen中的apply
        System.out.println(time.andThen(square).apply(2));
        //先执行compose再执行后的内容
        System.out.println(time.compose(square).apply(2));
        

    }
}

理解了Function,Consumer接口很类似,而他的参数只有一个

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值