• 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
  • Bear Bibeault
  • Paul Clapham
  • Jeanne Boyarsky
  • Knute Snortum
Sheriffs:
  • Liutauras Vilda
  • Tim Cooke
  • Junilu Lacar
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Joe Ess
  • salvin francis
  • fred rosenberger

Can we reuse the Streams

 
Ranch Hand
Posts: 157
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
 
Rancher
Posts: 3418
34
  • 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: 67443
257
  • 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: 9671
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.

 
We're being followed by intergalactic spies! Quick! Take this tiny ad!
Sauce Labs - World's Largest Continuous Testing Cloud for Websites and Mobile Apps
https://coderanch.com/t/722574/Sauce-Labs-World-Largest-Continuous
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!