How to use Streams api peek() function and make it work?

◇◆丶佛笑我妖孽 提交于 2019-12-08 05:43:30

问题


According to this question, 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 :

lol

Thus, how can I make the peek function actually work?

If there is no way to that so whats the point of using peek?


回答1:


You have to use terminal operation 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();

Or replace peek with forEach (which is terminal):

    ss.parallel().forEach(System.out::println);



回答2:


peek() method uses Consumer as parameter which means that potentially you can mutate the state of the incoming element. At the same time Java documentation says that peek should be mostly used for debugging purposes. It is an intermediate operator and requires a terminal operator like forEach.

stream().peek(Consumer).forEach(Consumer);


来源:https://stackoverflow.com/questions/38424828/how-to-use-streams-api-peek-function-and-make-it-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!