Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

2
  • I'm not sure this is correct advice: he could use forEachOrdered instead of forEach if he wanted to use a parallel stream but still preserve the order. But as the documentation for forEach states, preserving the encounter order sacrifices the benefit of parallelism. I suspect that is also the case with toList then.
    – herman
    Commented Feb 4, 2015 at 11:08
  • OK. According to docs.oracle.com/javase/tutorial/collections/streams/… the collect method is designed to perform the most common stream operations that have side effects in a parallel-safe manner. Operations like forEach and peek ... if you use one of these operations with a parallel stream, then the Java runtime may invoke the lambda expression that you specified as its parameter concurrently from multiple threads. So it carefully has some things atomic and some not. Weird. Assuming that is the case, option 1, if made parallel, might have contention issues...
    – rogerdpack
    Commented Jan 29, 2021 at 17:38