java function 使用_Java8新特性Function、BiFunction使用

packagecom;importjava.util.function.BiFunction;importjava.util.function.Function;public classDemoFunction {public static voidmain(String[] args) {

DemoFunction t1= newDemoFunction();//Function函数的使用

Integer addResult = t1.compute(3, value -> value +value);

System.out.println("加法结果:" +addResult);

Integer subResult= t1.compute(3, value -> value - 1);

System.out.println("减法结果:" +subResult);

Integer multipResult= t1.compute(3, value -> value *value);

System.out.println("乘法结果:" +multipResult);

Integer divisionResult= t1.compute(6, value -> value / 3);

System.out.println("除法结果:" +divisionResult);//使用compose场景, 从右向左处理, 这里就是 (6 * 6) + 10 = 46

Integer composeResult = t1.computeForCompose(6,

value-> value + 10,

value-> value *value);

System.out.println("Function compose 结果:" +composeResult);//使用andThen场景, 从左向右处理, 这里就是(3 + 20) - 10 = 13

Integer andThenResult = t1.computeForAndThen(3,

value-> value + 20,

value-> value - 10);

System.out.println("Function andThen 结果:" +andThenResult);//使用 BiFunctioin场景, 这里是 2 + 3 = 5

Integer biFuncResult = t1.computeForBiFunction(2, 3,

(v1, v2)-> v1 +v2);

System.out.println("BiFunction 结果:" +biFuncResult);//使用 BiFunctioin andThen场景, 这里是 (2 * 3) + 6 = 12

Integer biFuncAndThenResult = t1.computeForBiFunctionAndThen(2, 3,

(v1, v2)-> v1 * v2, v1 -> v1 + 6);

System.out.println("BiFunction andThen 结果:" +biFuncAndThenResult);

}/***@paramnum

*@paramfunction

*@return* @desc 使用JDK8 Function函数*/

private Integer compute(Integer num, Functionfunction) {

Integer result=function.apply(num);returnresult;

}/***@paramnum

*@paramfunction1

*@paramfunction2

*@return* @desc 使用compose函数,简单的说,就是从右向左处理。*/

privateInteger computeForCompose(Integer num,

Functionfunction1,

Functionfunction2) {returnfunction1.compose(function2).apply(num);

}/***@paramnum

*@paramfunction1

*@paramfunction2

*@return* @desc 使用andThen函数,简单的说,就是从左向右处理。*/

privateInteger computeForAndThen(Integer num,

Functionfunction1,

Functionfunction2) {returnfunction1.andThen(function2).apply(num);

}/***@paramnum1

*@paramnuum2

*@parambiFunction

*@return* @desc 使用BiFunction*/

privateInteger computeForBiFunction(Integer num1, Integer num2,

BiFunctionbiFunction) {returnbiFunction.apply(num1, num2);

}/***@paramnum1

*@paramnum2

*@parambiFunction

*@paramfunction

*@return* @desc 使用BiFunction andThen方法*/

privateInteger computeForBiFunctionAndThen(Integer num1, Integer num2,

BiFunctionbiFunction,

Functionfunction) {returnbiFunction.andThen(function).apply(num1, num2);

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值