Java 8与Java 9中的Stream.peek()方法 [英] Stream.peek() method in Java 8 vs Java 9

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

问题描述

我正在学习Java 8 lambda表达式,并想询问以下与 peek 方法in我遇到的函数接口。

I am in the progress of learning through Java 8 lambda expressions and would like to ask about the following piece of Java code relating to the peek method in the function interface that I have come across.

在IDE上执行程序时,它没有输出。我原以为它会给 2,4,6

On execution of the program on IDE, it gives no output. I was expecting it would give 2, 4, 6.

import java.util.Arrays;
import java.util.List;

public class Test_Q3 {

    public Test_Q3() {
    }

    public static void main(String[] args) {
        List<Integer> values = Arrays.asList(1, 2, 3);
        values.stream()
              .map(n -> n * 2)
              .peek(System.out::print)
              .count();
    }
}


推荐答案

我假设你在Java 9下运行它?您没有更改流的 SIZED 属性,因此无需执行 map peek

I assume you are running this under Java 9? You are not altering the SIZED property of the stream, so there is no need to execute either map or peek at all.

换句话说,你所关心的只是 count 作为最终结果,但与此同时,您不会以任何方式更改列表的初始大小(通过 filter 例如或 distinct )这是在Streams中完成的优化。

In other words all you care is about count as the final result, but in the meanwhile you do not alter the initial size of the List in any way (via filter for example or distinct) This is an optimization done in the Streams.

顺便说一下,即使你添加一个虚拟过滤器,这也会显示你的期望:

Btw, even if you add a dummy filter this will show what you expect:

values.stream ()
      .map(n -> n*2)
      .peek(System.out::print)
      .filter(x -> true)
      .count();

这篇关于Java 8与Java 9中的Stream.peek()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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