使用流执行此操作的最佳方法是使用
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秒。



