Win a copy of TensorFlow 2.0 in Action this week in the Artificial Intelligence and Machine Learning forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Paul Clapham
  • Bear Bibeault
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Jj Roberts
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • salvin francis
  • Scott Selikoff
  • fred rosenberger

Can we reuse the Streams

 
Ranch Hand
Posts: 161
1
jQuery Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I am practising OCP questions by Enthuware and the code is as follows:



Can we reuse the stream as i used stream once with dList and also the second time.

Thanks & Regards,

Swapna
 
Master Rancher
Posts: 3701
44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As you did, yes.  That is, you didn't actually re-use the same stream.  You re-used the same List (dList), and you called stream() twice to get two different streams.  Each of those streams was used once, calling the forEach() method once on each one.  That's fine.  However you can't call forEach() twice on the same Stream instance.  Or more generally, you can't call more than one terminal operation on a given Stream instance.  

So you can't do this:
 
Marshal
Posts: 70701
288
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As Mike has suggested, you can't use the same Stream twice, but you have two separate Streams in that code.
Tell us, will line 6 cause 10.0, 20.0 to be printed, or 20.0, 30.0?
 
Sheriff
Posts: 9674
42
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The stream package javadoc sums it up pretty well.

javadoc wrote:Consumable. The elements of a stream are only visited once during the life of a stream. Like an Iterator, a new stream must be generated to revisit the same elements of the source.

 
The first person to drink cow's milk. That started off as a dare from this tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic