Closed rljw closed 3 years ago
Hi, the way this stream was constructed is flawed. This is because there are side effects in this stream, where s, a local variable outside of the lambda expression is being manipulated. But the stream works fine because the .forEach(x -> ...) method allows side effects to occur. A better way to construct the stream would be to use the reduce method. Hope this helps!
int s = IntStream.range(1,100).boxed().reduce(0, (x,y) -> x + y); s;
I did a similar method to @brendancjz. I thought that since the purpose of the stream was just to sum up integers 1 to 99, I didn't see a need to store the result. I also didn't see a need to box the IntStream, so I simply did:
IntStream.range(1,100).reduce(0, (x,y) -> x + y)
Ah I get it now, thank you guys!
hello does anyone know how to do part e for this qn?
I used this reduce method. The accumulator I used (x,y) -> x + y.length(), and the combiner u can just use (p,q) -> p to reduce the stream to the first element.
hello does anyone know how to do part e for this qn?
Hi @Zekeseoj, what I did was add all the words into one line of string before calculating the length.
reduce("", (x,y) -> x + y).length()
It's an alternative solution that seems to get the answer, so hope this helps!
Hi, anyone had any comments for part (b)? I'm not too sure what is expected, as the stream seems to work fine