[Solved] Java stream, difference between with and without forEach


peek is just a way to peek inside the stream, it doesn’t change it but the function in peek will receive all the elements that are in the stream.

forEach is an terminal operation that will consume all the data in the stream and return void.

The result of the above code will be each number printed twice, when you remove peek you will get the numbers printed only once.

If you remove forEach you wont’ get any output because stream won’t execute the actions until the terminal operation (like e.g. forEach, count) is encountered.

2

solved Java stream, difference between with and without forEach