Java 8 - 转换列表的最佳方法:map还是foreach? [英] Java 8 - Best way to transform a list: map or foreach?
问题描述
我有一个列表 myListToParse
其中我想过滤元素并对每个元素应用一个方法,并将结果添加到另一个列表中 myFinalList
。
I have a list myListToParse
where I want to filter the elements and apply a method on each element, and add the result in another list myFinalList
.
在Java 8中,我注意到我可以通过两种不同的方式来实现。我想知道他们之间更有效的方式,并理解为什么一种方式比另一种更好。
With Java 8 I noticed that I can do it in 2 different ways. I would like to know the more efficient way between them and understand why one way is better than the other one.
我对任何有关第三种方式的建议持开放态度。
I'm open for any suggestion about a third way.
方法1:
myFinalList = new ArrayList<>();
myListToParse.stream()
.filter(elt -> elt != null)
.forEach(elt -> myFinalList.add(doSomething(elt)));
方法2:
myFinalList = myListToParse.stream()
.filter(elt -> elt != null)
.map(elt -> doSomething(elt))
.collect(Collectors.toList());
推荐答案
不要担心任何性能差异,他们'在这种情况下通常会最小化。
Don't worry about any performance differences, they're going to be minimal in this case normally.
方法2是首选,因为
-
它不需要改变存在于lambda表达式之外的集合,
it doesn't require mutating a collection that exists outside the lambda expression,
它更具可读性,因为它在收集管道按顺序写入(首先是过滤操作,然后是地图操作,然后收集结果),
(有关收集管道的好处的更多信息,请参阅Martin Fowler的优秀文章)
it's more readable because the different steps that are performed in the collection pipeline are written sequentially (first a filter operation, then a map operation, then collecting the result), (for more info on the benefits of collection pipelines, see Martin Fowler's excellent article)
您可以通过替换<$来轻松更改收集值的方式c $ c>使用的收集器。在某些情况下,您可能需要编写自己的收集器
,但之后的好处是您可以轻松地重复使用它。
you can easily change the way values are collected by replacing the Collector
that is used. In some cases you may need to write your own Collector
, but then the benefit is that you can easily reuse that.
这篇关于Java 8 - 转换列表的最佳方法:map还是foreach?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!