Java 8 Streams peek api [英] Java 8 Streams peek api

查看:207
本文介绍了Java 8 Streams peek api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 peek 尝试了以下Java 8代码片段。

I tried the following snippet of Java 8 code with 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);

我看到以下内容同时输出了peek和foreach调用。

I see the following which outputs both the peek as well as foreach invocation.

Bender
Bender
Fry
Fry
Leela
Leela

foreach peek 接受(消费者<?超级T>动作)
那么为什么输出不同?

Both foreach and peek take in a (Consumer<? super T> action) So why is the output different?

推荐答案

Javadoc 提到以下内容:


中间操作返回一个新流。他们总是懒惰;执行诸如filter()之类的中间操作实际上并不执行任何过滤,而是创建一个新流,当遍历时,该流包含与给定谓词匹配的初始流的元素。在执行管道的终端操作之前,不会开始遍历管道源。

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.

peek 作为中间操作什么都不做。在应用 foreach 之类的终端操作时,结果会打印出来。

peek being an intermediate operation does nothing. On applying a terminal operation like foreach, the results do get printed out as seen.

这篇关于Java 8 Streams peek api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆