What is the difference between .foreach and .stream().foreach?(.foreach 和 .stream().foreach 有什么区别?)
问题描述
这是一个例子:代码A:
This is a example: code A:
files.forEach(f -> {
//TODO
});
另外一个代码 B 可能会以这种方式使用:
and another code B may use on this way:
files.stream().forEach(f -> { });
两者有什么区别,有stream()
和没有stream()
?
What is the difference between both, with stream()
and no stream()
?
推荐答案
实际上,它们大多是相同的,只是语义上略有不同.
Practically speaking, they are mostly the same, but there is a small semantic difference.
代码 A 由 Iterable.forEach
定义,而代码 B 由 Stream.forEach
定义.Stream.forEach
的定义允许以任何顺序处理元素——即使是顺序流.(对于并行流,Stream.forEach
很可能会乱序处理元素.)
Code A is defined by Iterable.forEach
, whereas code B is defined by Stream.forEach
. The definition of Stream.forEach
allows for the elements to be processed in any order -- even for sequential streams. (For parallel streams, Stream.forEach
will very likely process elements out-of-order.)
Iterable.forEach
从源中获取一个 Iterator 并在其上调用 forEachRemaining()
.据我所见,集合类上 Stream.forEach
的所有当前(JDK 8)实现都将创建一个从源迭代器之一构建的 Spliterator,然后调用 forEachRemaining
在那个迭代器上——就像 Iterable.forEach
一样.所以他们做同样的事情,虽然流版本有一些额外的设置开销.
Iterable.forEach
gets an Iterator from the source and calls forEachRemaining()
on it. As far as I can see, all current (JDK 8) implementations of Stream.forEach
on the collections classes will create a Spliterator built from one of the source's Iterators, and will then call forEachRemaining
on that Iterator -- just like Iterable.forEach
does. So they do the same thing, though the streams version has some extra setup overhead.
但是,在未来,流的实现可能会发生变化,从而不再是这种情况.
However, in the future, it's possible that the streams implementation could change so that this is no longer the case.
(如果要保证处理流元素的顺序,请改用 forEachOrdered()
.)
(If you want to guarantee ordering of processing streams elements, use forEachOrdered()
instead.)
这篇关于.foreach 和 .stream().foreach 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:.foreach 和 .stream().foreach 有什么区别?
基础教程推荐
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01