Java 8 Stream - 过滤和foreach方法未按预期打印 [英] Java 8 Stream - Filter and foreach method not printing as expected

查看:1590
本文介绍了Java 8 Stream - 过滤和foreach方法未按预期打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在执行以下程序:

Stream.of("d2", "a2", "b1", "b3", "c")
.filter(s -> {
    System.out.println("filter: " + s);
    return true;
})
.forEach(s -> System.out.println("forEach: " + s));

我得到的输出是:

filter:  d2
forEach: d2
filter:  a2
forEach: a2
filter:  b1
forEach: b1
filter:  b3
forEach: b3
filter:  c
forEach: c

但是,我期待以下输出:

However, I was expecting the following output:

filter:  d2
filter:  a2
filter:  b1
filter:  b3
filter:  c 
forEach: d2
forEach: a2
forEach: b1
forEach: b3
forEach: c

含义,首先是过滤器方法循环应该已经完全执行,然后 forEach 方法循环应该已经开始。

Meaning, first the filter method loop should have executed completely and then the forEach method loop should have started.

我有什么问题吗?

推荐答案

您的期望是错的。

执行终端操作 forEach 时,它会消耗 Stream <的一个元素/ code>一次。它消耗的每个元素都必须通过 Stream 的所有中间操作,这会导致 filter 在元素上执行就在 forEach 之前在同一元素上执行(假设元素通过过滤器)。

When the terminal operation forEach is executed, it consumes one element of the Stream at a time. Each element it consumes has to pass all the intermediate operations of the Stream, which causes filter to be executed on the element just prior to forEach being executed on same element (assuming the element passes the filter).

换句话说,只要 Stream 过滤器就会懒惰地应用于每个元素c $ c>管道需要它的下一个元素(在你的情况下,下一个操作是 forEach )。

In other words, filter is lazily applied to each element just when the next operation in the Stream pipeline requires its next element (in your case the next operation is forEach).

这意味着如果你的终端操作只需要处理一些Stream元素(例如,如果用替换 forEach(),则findFirst()), filter()操作只会在第一个元素通过之前执行(在你的例子中,这意味着过滤器只会为第一个元素)。

This means that if your terminal operation would only require some of the Stream elements to be processed (for example, if you replaced forEach() with findFirst()), the filter() operation would only be executed until the first element passes it (which in your example means the filter will be executed only for the first element).

这篇关于Java 8 Stream - 过滤和foreach方法未按预期打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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