USER USER - 5 months ago 15
Java Question

Java stream, difference between with and without forEach

What is the difference between with (*) forEach and without? What is the output and why? I know without forEach nothing will be printed...but why peek is needed?

As I know for

peek
you have to do something with the resulting stream for System.out.println to do anything... however it doesn't seems to be done here, and it still run....

public class NaturalNumbers
implements Supplier<Integer> {
private int i = 0;
public Integer get() { return ++i; }
}

public static void main(String[] args) {
Stream<Integer> s =
Stream.generate(new NaturalNumbers());

s.limit(5)
.peek( System.out::println )
.forEach( System.out::println );/// ׂ (*)
{

Answer

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.