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?

marked as duplicate by Roman C java Feb 15 at 3:53

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    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().

    • Does the non-guarantee of encounter order of forEach also apply to non parallel streams that have ordered source?– tsolakpFeb 14 at 21:36
    • 2
      @tsolakp Briefly, yes. See here for more: stackoverflow.com/q/34247318/1553851– shmoselFeb 14 at 21:40
    • 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;"– tsolakpFeb 14 at 21:48
    • @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.– EugeneFeb 14 at 21:57
    • 2
      @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.– shmoselFeb 14 at 22:14

    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.

      Not the answer you're looking for? Browse other questions tagged or ask your own question.