流和懒惰的评估 [英] Stream and lazy evaluation

查看:95
本文介绍了流和懒惰的评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 java 8关于流抽象的API 但是
我不太理解这句话:

I'm reading from the java 8 API on the stream abstraction but I don't understand this sentence very well:


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

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.

当过滤操作创建时新流是否包含已过滤的元素?
似乎可以理解,流只在遍历时才包含元素,即终端操作。但是,包含过滤流的内容是什么?我糊涂了!!!

When a filter operation creates a new stream does that stream contains filtered element? It seems to understand that the stream contains elements only when it is traversed i.e with a terminal operation. But, than, what does contains the filtered stream? I'm confused!!!

推荐答案

这意味着过滤器仅在终端操作期间应用。想想这样的事情:

It means that the filter is only applied during the terminal operation. Think of something like this:

public Stream filter(Predicate p) {
    this.filter = p; // just store it, don't apply it yet
    return this; // in reality: return a new stream
}
public List collect() {
    for (Object o : stream) {
        if (filter.test(o)) list.add(o);
    }
    return list;
}

(这不是编译,是对现实的简化,但原则是那里)

(That does not compile and is a simplification of the reality but the principle is there)

这篇关于流和懒惰的评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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