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 "
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.
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):