本文介绍了.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()。据我所知,集合类上的所有当前(JDK 8) Stream.forEach 的实现都将创建一个源自其中一个迭代器的Spliterator,然后在Iterator上调用 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 14:01