Java 8 Streams peek api
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29586014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java 8 Streams peek api
提问by Neo
I tried the following snippet of Java 8 code with peek
.
我尝试了以下 Java 8 代码片段peek
。
List<String> list = Arrays.asList("Bender", "Fry", "Leela");
list.stream().peek(System.out::println);
However there is nothing printed out on the console. If I do this instead:
但是,控制台上没有打印任何内容。如果我这样做:
list.stream().peek(System.out::println).forEach(System.out::println);
I see the following which outputs both the peek as well as foreach invocation.
我看到以下输出 peek 和 foreach 调用。
Bender
Bender
Fry
Fry
Leela
Leela
Both foreach
and peek
take in a (Consumer<? super T> action)
So why is the output different?
双方foreach
并peek
参加一个 (Consumer<? super T> action)
那么,为什么是输出有什么不同?
回答by Neo
The Javadocmentions the following:
该Javadoc中提到以下:
Intermediate operations return a new stream. They are always lazy; executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate. Traversal of the pipeline source does not begin until the terminal operation of the pipeline is executed.
中间操作返回一个新的流。他们总是懒惰;执行诸如 filter() 之类的中间操作实际上并不执行任何过滤,而是创建一个新流,该流在遍历时包含与给定谓词匹配的初始流的元素。管道源的遍历直到管道的终端操作被执行后才开始。
peek
being an intermediate operation does nothing. On applying a terminal operation like foreach
, the results do get printed out as seen.
peek
作为中间操作什么都不做。在应用像 那样的终端操作时foreach
,结果确实被打印出来了。
回答by Paul Boddington
The documentation for peek
says
的文档peek
说
Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream. This is an intermediate operation.
返回一个由该流的元素组成的流,另外在每个元素上执行提供的操作,因为元素从结果流中被消耗。这是一个中间操作。
You therefore have to do something with the resulting stream for System.out.println
to do anything.
因此,您必须对结果流做一些事情System.out.println
才能做任何事情。
回答by James Montagne
回答by Akshay Lokur
Streams in Java-8 are lazy, in addition, say if there are two chained operations in stream one after the other, then the second operation begins as soon as first one finishes processing a unit of data element (given there is a terminal operation in the stream).
Java-8 中的流是惰性的,另外,如果流中有两个链式操作一个接一个,那么第二个操作会在第一个操作完成处理一个数据元素单元后立即开始(假设在流)。
This is the reason why you can see repeated name strings getting output.
这就是为什么您可以看到重复的名称字符串获得输出的原因。