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

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

问题描述

我正在学习 Java 8 lambda 表达式,想询问与 peek 方法在我拥有的函数接口中遇到.

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 属性,因此根本不需要执行 mappeek.

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 作为最终结果,但同时您不会更改 any 中 List 的初始大小 方式(例如通过 filterdistinct) 这是在 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天全站免登陆