USER USER - 1 year ago 130
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

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());

.peek( System.out::println )
.forEach( System.out::println );/// ׂ (*)

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download