• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why do I need to call collect on a Stream before anything side effect happens ?

 
Pho Tek
Ranch Hand
Posts: 782
Chrome Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I wrote this piece of code, nothing was written to the console.

The correct way is to call collect on the Stream<Integer>. Why?

And if I call forEach on the Stream<Integer>, I get a surprising result different from calling collect.



 
Venkat Subramaniam
Author
Ranch Hand
Posts: 109
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One of the tenets of FP is immutability. We do not mutate and especially mutate shared state. If we mutate state and cause side effects,
it will mess up several things that are possible in FP - referential transparency, lazy evaluations, potential concurrency and re-orderings.

Please see the link below:

"We should use extra caution not to mix mutability, shared state, and functional style.-->Can you just give me a rough example on this statement "

from Discussion on FP and mutability

If the goal is to transform one list to another, then do the transformation first, using map, keeping the transformatio operation pure. Then convert the
abstraction of stream to a concrete collection, like list.
 
Rob Spoor
Sheriff
Posts: 20817
68
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pho Tek wrote:And if I call forEach on the Stream<Integer>, I get a surprising result different from calling collect.




Surprising to you maybe. I expected a true for each element. The reason is the call to map. This takes your Stream<String>, and applies the transformation function to each element. That transformation function, res.add(Integer.parseInt(v)) parses the String and adds it to the List. However, the add method returns true, and that is what the element is replaced with.

If you want to print each String as an Integer, change the map function to one of these (their equivalent):
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!