java函数式编程

        Lambda 表达式是 JDK8以后 的一个新特性,可以取代大部分的匿名内部类,写出更优雅的 Java 代码,尤其在集合的遍历和其他集合操作中,可以极大地优化代码结构。

        java提供两类常用的函数,Consumer消费函数,Supplier供给函数。使@FunctionalInterface

注解定义函数接口。

        在项目开发中,有时候流程控制if语句比较多,可以使用函数编程有效的消除if嵌套

一、定义函数

@FunctionalInterface
public interface ISupplier<T,U> {
    U  compose(T t);
}

@FunctionalInterface
public interface IConsumer<T> {
    void  apply(T t);
}

public interface IExecutor<U> {
    U  exec(U u);
}

二、封装函数工具

public class FunUtils<T,U,R> {

    private  volatile U  result ;

    public  static  <T> void run(boolean isTrue,T t, IConsumer<T> fun){
        if(isTrue){
            run(t,fun);
        }
    }

    public  static  <T,U,R> FunUtils<T,U,R>  run(T t, IConsumer<T> fun){
        FunUtils<T,U,R>  instance = new FunUtils<>();
        fun.apply(t);
        return  instance;
    }

    public  FunUtils<T,U,R>  runThen(T t,ISupplier<T,U> supplier ,IExecutor<U> executor){
        if(Objects.nonNull(t)){
            U compose = supplier.compose(t);
            executor.exec(compose);
        }
        return  this;
    }

    public  static  <T,U,R> FunUtils<T,U,R> accept(boolean isTrue,T t, ISupplier<T,U> fun){
        return  isTrue?accept(t,fun):new FunUtils<>();
    }

    public  static  <T,U,R> FunUtils<T,U,R> accept(T t, ISupplier<T,U> fun){
        FunUtils<T,U,R>  instance = new FunUtils<>();
        U u = fun.compose(t);
        instance.set(u);
        return instance;
    }

    public FunUtils<T,U,R> acceptThen(IExecutor<U> executor){
        U u = this.get();
        if(Objects.nonNull(u)){
            U newVal = executor.exec(u);
            this.set(newVal);
        }
        return  this;
    }


    public U get() {
        return result;
    }

    private void set(U result) {
        this.result = result;
    }

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值