.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.)
相关文章