问题描述
根据, peek()
很懒,这意味着我们应该以某种方式激活它。事实上,要激活它以向控制台输出内容我尝试了这个:
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
因此,如何让 peek
函数真正起作用?
Thus, how can I make the peek
function actually work?
如果没有办法,那么使用 peek
是什么意思?
If there is no way to that so whats the point of using peek
?
推荐答案
你必须使用在流上执行(peek不是终端,它是一个中间操作,返回一个新流),例如count():
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();
或用<$ c $替换 peek
c> forEach (这是终端):
Or replace peek
with forEach
(which is terminal):
ss.parallel().forEach(System.out::println);
这篇关于如何使用Streams api peek()函数并使其工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!