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;
}
}