Home > database >  Terminal operations on streams cannot be chained?
Terminal operations on streams cannot be chained?

Time:01-04

I have this concern when it is said there can be one terminal operation and terminal operations cannot be chained. we can write something like this right? Stream1.map().collect().forEach() Isn’t this chaining collect and forEach which are both terminal operations. I don’t get that part

The above works fine

CodePudding user response:

Because

  1. Assuming you meant collect(Collectors.toList()), forEach is a List operation, not a Stream operation. Perhaps the source of your confusion: there is a forEach method on Stream as well, but that's not what you're using.
  2. Even if it weren't, nothing stops you from creating another stream from something that can be streamed, you just can't use the same stream you created in the first place.

CodePudding user response:

Stream has forEach, and List has forEach (by extending Iterable). Different methods, but with the same name and purpose. Only the former is a terminal operation.

One practical difference is that the Stream version can be called on a parallel stream, and in that case, the order is not guaranteed. It might appear "random". The version from Iterable always happens on the same, calling thread. The order is guaranteed to match that of an Iterator.

Your example is terminally collecting the stream's items into a List, then calling forEach on that List.

That example is bad style because the intermediate List is useless. It's creating a List for something you could have done directly on the Stream.

  • Related