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?

fps
  • 33,623
  • 8
  • 55
  • 110
Shell Scott
  • 1,679
  • 18
  • 28

2 Answers2

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

shmosel
  • 49,289
  • 6
  • 73
  • 138
  • Does the non-guarantee of encounter order of `forEach` also apply to non parallel streams that have ordered source? – tsolakp Feb 14 '18 at 21:36
  • 2
    @tsolakp Briefly, yes. See here for more: https://stackoverflow.com/q/34247318/1553851 – shmosel Feb 14 '18 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;" – tsolakp Feb 14 '18 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. – Eugene Feb 14 '18 at 21:57
  • @tsolakp Presumably that doesn't apply to operations involving side-effects, since they depend on unknown variables. But I agree that the language could be tightened up. – shmosel Feb 14 '18 at 22:07
  • 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.* – shmosel Feb 14 '18 at 22:14
  • @shmosel exactly, but that would count as a difference between them – Eugene Feb 15 '18 at 08:00
  • I don't see why. – shmosel Feb 15 '18 at 08:01
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.

Grzegorz Piwowarek
  • 13,172
  • 8
  • 62
  • 93