java lambda无法使用_Lambda中的Java 8 Lambda无法修改外部Lambda中的变量

小编典典

使用流执行此操作的最佳方法是使用reduce:

// make a transformer that combines all of them as one

Transformer combinedTransformer =

// the stream of transformers

transformers.stream()

// combine all the transformers into one

.reduce(

// apply each of the transformers in turn

(t1, t2) -> x -> t2.apply(t1.apply(x)))

);

// the stream of strings

strings.stream()

// transform each string with the combined transformer

.map(combinedTranformer::apply);

当然,这是假定transformers非空的。如果有可能为空,则使用的两个参数重载来reduce代替就足够简单了,就像这样(假定Tranformer是一个功能接口):

// make a transformer that combines all of them as one

Transformer combinedTransformer =

// the stream of transformers

transformers.stream()

// combine all the transformers into one

.reduce(

// the no-op transformer

x -> x,

// apply each of the transformers in turn

(t1, t2) -> x -> t2.apply(t1.apply(x)))

);

// the stream of strings

strings.stream()

// transform each string with the combined transformer

.map(combinedTranformer::apply);

出现编译器错误的原因是,如错误所述,lambda表达式中使用的外部变量必须 有效地是final

;也就是说,声明它们final(如果尚未声明)不得更改程序的含义,也不得更改程序是否编译。因此,通常禁止在lambda中使用可变分配,这有充分的理由:突变会破坏并行化,而Java

8中包含lambda的主要原因之一是允许更轻松的并行编程。

一般来说,只要您想以某种方式“总结”结果,reduce(无论是三个重载中的任何一个)都是您的首选方法。学习如何使用map,filter,reduce,和flatMap有工作的时候实际上是非常重要Stream秒。

2020-11-19

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值