Stream and lazy evaluation(流式评估和惰性评估)
问题描述
我正在阅读 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() 之类的中间操作实际上并不执行任何过滤,而是创建一个新流,当遍历,包含初始流中匹配的元素给定谓词.管道源的遍历直到执行管道的终端操作.
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 contain a filtered element? It seems to understand that the stream contains elements only when it is traversed i.e with a terminal operation. But, then, what does the filtered stream contain? 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)
这篇关于流式评估和惰性评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:流式评估和惰性评估
基础教程推荐
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 降序排序:Java Map 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01