ekjcfn3902039
ekjcfn3902039

Reputation: 1839

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

Upvotes: 3

Views: 1177

Answers (2)

Journeycorner
Journeycorner

Reputation: 2542

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.

Upvotes: 4

Tomasz R
Tomasz R

Reputation: 298

It does the same job, however the paradigm is completely different.

Streams are a part of functional programming which lets you think in terms of what to do and not how.

I know it may sound abstract, but it really makes sense. So basically you focus on operations and not iterations. Not to mention that stream() offers you additional functionality like filter, map, reduce...

And parallelStream will enable you to use all your cores, which is pretty cool - you will have a truly multithreaded application without a single extra line of code.

Upvotes: 0

Related Questions