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 有什么区别?
- 如何指定 CORS 的响应标头? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 转换 ldap 日期 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 获取数字的最后一位 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01