妙用Java 8中的 Function接口 消灭if...else(非常新颖的写法)
阅读本文大概需要 3 分钟。
来自:juejin.cn/post/7011435192803917831
if (...){throw new RuntimeException("出现异常了");}if (...){doSomething();} else {doOther();}
Function可以看作转换型函数 




/*** 抛异常接口**/@FunctionalInterfacepublic interface ThrowExceptionFunction {/*** 抛出异常信息** @param message 异常信息* @return void**/void throwMessage(String message);}
/*** 如果参数为true抛出异常** @param b* @return com.example.demo.func.ThrowExceptionFunction**/public static ThrowExceptionFunction isTure(boolean b){return (errorMessage) -> {if (b){throw new RuntimeException(errorMessage);}};}


/*** 分支处理接口**/@FunctionalInterfacepublic interface BranchHandle {/*** 分支操作** @param trueHandle 为true时要进行的操作* @param falseHandle 为false时要进行的操作* @return void**/void trueOrFalseHandle(Runnable trueHandle, Runnable falseHandle);}
/*** 参数为true或false时,分别进行不同的操作** @param b* @return com.example.demo.func.BranchHandle**/public static BranchHandle isTureOrFalse(boolean b){return (trueHandle, falseHandle) -> {if (b){trueHandle.run();} else {falseHandle.run();}};}


/*** 空值与非空值分支处理*/public interface PresentOrElseHandler<T extends Object> {/*** 值不为空时执行消费操作* 值为空时执行其他的操作** @param action 值不为空时,执行的消费操作* @param emptyAction 值为空时,执行的操作* @return void**/void presentOrElseHandle(Consumer<? super T> action, Runnable emptyAction);}
/*** 参数为true或false时,分别进行不同的操作** @param b* @return com.example.demo.func.BranchHandle**/public static PresentOrElseHandler> isBlankOrNoBlank(String str){return (consumer, runnable) -> {if (str == null || str.length() == 0){runnable.run();} else {consumer.accept(str);}};}


推荐阅读:
心态崩了!税前2万4,到手1万4,年终奖扣税方式1月1日起施行~
内容包含Java基础、JavaWeb、MySQL性能优化、JVM、锁、百万并发、消息队列、高性能缓存、反射、Spring全家桶原理、微服务、Zookeeper、数据结构、限流熔断降级......等技术栈!
⬇戳阅读原文领取!                                       朕已阅 
评论

