ekjcfn3902039 ekjcfn3902039 - 2 months ago 18
Java Question

Java 8 Collection and stream/forEach

Is there any reason to specifically insert a stream/parallel stream before a forEach call when using a Collection?

Example:

Collection<Object> foo;
foo.forEach(); // Goes through every item in foo
foo.stream().forEach(); // Does stream make a difference here
foo.parallelStream().forEach(); // Does this make a difference here?


Thanks

Answer
foo.forEach(); // Goes through every item in foo
foo.stream().forEach(); // Does stream make a difference here

It is useless unless you need stream operations like map or filter.

foo.parallelStream().forEach();

This spawns a new thread for every logical core of your computer to compute the items. Think twice about whether or not you use this feature, in most cases it only pays off on long running operations.

Bottom line: Streams really shine when they can be used without side-effects, like mapping collection of type A to type B, without altering A. Loops most likely will alter data outside the stream.