Java 8 - Best way to transform a list: map or foreach?

前端 未结 8 1878
隐瞒了意图╮
隐瞒了意图╮ 2020-12-07 07:01

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.

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-07 07:41

    I agree with the existing answers that the second form is better because it does not have any side effects and is easier to parallelise (just use a parallel stream).

    Performance wise, it appears they are equivalent until you start using parallel streams. In that case, map will perform really much better. See below the micro benchmark results:

    Benchmark                         Mode  Samples    Score   Error  Units
    SO28319064.forEach                avgt      100  187.310 ± 1.768  ms/op
    SO28319064.map                    avgt      100  189.180 ± 1.692  ms/op
    SO28319064.mapWithParallelStream  avgt      100   55,577 ± 0,782  ms/op
    

    You can't boost the first example in the same manner because forEach is a terminal method - it returns void - so you are forced to use a stateful lambda. But that is really a bad idea if you are using parallel streams.

    Finally note that your second snippet can be written in a sligthly more concise way with method references and static imports:

    myFinalList = myListToParse.stream()
        .filter(Objects::nonNull)
        .map(this::doSomething)
        .collect(toList()); 
    

提交回复
热议问题