According to <a href="https://stackoverflow.com/questions/29586014/java-8-streams-peek-api" rel="nofollow">this question</a>,
peek() is lazy it means we should somehow activate it. In fact, to activate it to print something out to the console I tried this :
Stream<String> ss = Stream.of("Hi","Hello","Halo","Hacker News"); ss.parallel().peek(System.out::println); System.out.println("lol"); // I wrote this line to print sth out to terminal to wake peek method up
But that doesn't work and the output is :
Thus, how can I make the
peek function actually work?
If there is no way to that so whats the point of using
You have to use <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps" rel="nofollow">terminal operation</a> on a stream for it to execute (peek is not terminal, it is an intermediate operation, that returns a new Stream), e.g. count():
Stream<String> ss = Stream.of("Hi","Hello","Halo","Hacker News"); ss.parallel().peek(System.out::println).count();
forEach (which is terminal):
peek() method uses Consumer as parameter which means that <strong>potentially you can mutate the state of the incoming element</strong>. <strong>At the same time Java documentation says that peek should be mostly used for debugging purposes.</strong> It is an intermediate operator and requires a terminal operator like forEach.