2

Starts from java 8 to iterate throug list I can use both:

List list = new ArrayList(); 1. list.forEach(...) 2. list.stream().forEach(...) 

Is it any advantages of using second case? To convert list to stream?

0

2 Answers 2

6

There are no advantages of using the second case, unless you have a parallel stream. There is a disadvantage, namely that Stream.forEach() doesn't guarantee to respect encounter order. A more accurate (but still unnecessary) equivalent would be Stream.forEachOrdered().

Sign up to request clarification or add additional context in comments.

8 Comments

Does the non-guarantee of encounter order of forEach also apply to non parallel streams that have ordered source?
@tsolakp Briefly, yes. See here for more: stackoverflow.com/q/34247318/1553851
Someone got to write better Javadoc:). Here is snippet from Javadoc as well. "If a stream is ordered, repeated execution of identical stream pipelines on an identical source will produce an identical result;"
@shmosel plus one, I just did not find the right words that even if forEach operates only via side-effects, adding elements to a list via stream().forEach is strongly discouraged and it might produce wrong results, while the other one would be ok.
@Eugene OP never mentioned such a use. As for side-effects in general, I'll just quote the docs: A small number of stream operations, such as forEach() and peek(), can operate only via side-effects; these should be used with care.
|
2

No, in theory, the second option is worse than the first one - you pay the cost of instantiation/garbage-collection and calling a Stream instance and don't really get any benefit in return.

Additionally, in theory the iteration order of Stream.forEach() isn't deterministic.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.