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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With