有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java 8流peek api

我用^{尝试了以下Java 8代码片段

List<String> list = Arrays.asList("Bender", "Fry", "Leela");
list.stream().peek(System.out::println);

但是,控制台上没有打印任何内容。如果我这样做:

list.stream().peek(System.out::println).forEach(System.out::println);

我看到以下输出peek和foreach调用的代码

Bender
Bender
Fry
Fry
Leela
Leela

无论是foreach还是peek都有一个(Consumer<? super T> action) 那么,为什么输出不同呢


共 (4) 个答案

  1. # 1 楼答案

    Java-8中的流是惰性的,此外,如果流中有两个链式操作,那么第二个操作将在第一个操作处理完一个数据元素单元后开始(假设流中有一个终端操作)

    这就是为什么可以看到重复的名称字符串得到输出的原因

  2. # 2 楼答案

    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.

    peek作为中间操作没有任何作用。在应用像foreach这样的终端操作时,结果确实会打印出来,如图所示

  3. # 3 楼答案

    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.

    因此,您必须对System.out.println的结果流执行某些操作

  4. # 4 楼答案

    Stream上的文档中可以看到peek方法:

    ...additionally performing the provided action on each element as elements are consumed from the resulting stream.