栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Lambda中的Java 8 Lambda无法修改外部Lambda中的变量

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Lambda中的Java 8 Lambda无法修改外部Lambda中的变量

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

reduce

// make a transformer that combines all of them as oneTransformer 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 stringsstrings.stream()// transform each string with the combined transformer.map(combinedTranformer::apply);

当然,这是假定

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

// make a transformer that combines all of them as oneTransformer 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 stringsstrings.stream()// transform each string with the combined transformer.map(combinedTranformer::apply);

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

final
(如果尚未声明)不得更改程序的含义,也不得更改程序是否编译。因此,通常禁止在lambda中使用可变分配,这有充分的理由:突变会破坏并行化,而Java
8中包含lambda的主要原因之一是允许更轻松的并行编程。

一般来说,只要您想以某种方式“总结”结果,

reduce
(无论是三个重载中的任何一个)都是您的首选方法。学习如何使用
map
filter
reduce
,和
flatMap
有工作的时候实际上是非常重要
Stream
秒。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/454856.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号