使用jdk8 Function 函数式接口 实现方法的链式编程

Function函数提供了 compost 和 andThen 两个方法,来实现方法的链式编程

     // 将参数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));
    }
public class FunctionTest {

    private static List<Function<Integer,Integer>> list = new ArrayList<>();
    private static Function<Integer,Integer> a = value -> value + 10 ;
    private static Function<Integer,Integer> b = value -> value + 20 ;
    private static Function<Integer,Integer> c = value -> value + 30 ;
    private static Function<Integer,Integer> d = value -> value * 2 ;


    static {
        list = Arrays.asList(a,b,c,d);
    }
    
    public static void main(String[] args) {
        FunctionTest functionTest = new FunctionTest();
        System.out.println(functionTest.computeByDESC(2, list));// 64
        System.out.println(functionTest.computeByASC(2, list)); // 124


    }

    /**
     *  倒叙执行
     */
    public int computeByDESC(int a, List<Function<Integer,Integer>> list){
        Function<Integer,Integer> result = list.get(0);
        for (int i = 0; i < list.size(); i++) {
            if(i+1<list.size()){
                result =  result.compose(list.get(i+1));
            }
        }
        return result.apply(a);
    }

    /**
     *  正序执行
     */
    public int computeByASC(int a, List<Function<Integer,Integer>> list){
        Function<Integer,Integer> result = list.get(0);
        for (int i = 0; i < list.size(); i++) {
            if(i+1<list.size()){
                result =  result.andThen(list.get(i+1));
            }
        }
        return result.apply(a);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值