Java8中Iterator和Spliterator的区别 [英] Difference between Iterator and Spliterator in Java8
问题描述
我在学习时了解到Parallelism
是Spliterator
的主要优势.
I came to know while studying that Parallelism
is a main advantage of Spliterator
.
这可能是一个基本问题,但谁能解释一下 Iterator
和 Spliterator
之间的主要区别并举例说明?
This may be a basic question but can anyone explain me the main differences between Iterator
and Spliterator
and give some examples?
推荐答案
对我来说,这些名称几乎一目了然.Spliterator
== Splittable Iterator :它可以拆分一些源,也可以迭代它.它具有与 Iterator
大致相同的功能,但有一个额外的东西,它可以拆分成多个部分:这就是 trySplit
为了.并行处理需要拆分.
The names are pretty much self-explanatory, to me. Spliterator
== Splittable Iterator : it can split some source, and it can iterate it too. It roughly has the same functionality as an Iterator
, but with the extra thing that it can potentially split into multiple pieces: this is what trySplit
is for. Splitting is needed for parallel processing.
Iterator
总是有一个未知的大小:你只能通过 hasNext/next
遍历元素;Spliterator
可以提供大小(从而也在内部改进其他操作);通过 getExactSizeIfKnown
获得精确的值或通过 estimateSize
获得的近似值.
An Iterator
always has an unknown size: you can traverse elements only via hasNext/next
; a Spliterator
can provide the size (thus improving other operations too internally); either an exact one via getExactSizeIfKnown
or a approximate via estimateSize
.
另一方面,tryAdvance
是 hasNext/next
来自 Iterator
的东西,但它是一个单一的方法,更容易推理关于,海事组织.与此相关的是 forEachRemaining
,它在默认实现中委托给 tryAdvance
,但它不必总是这样(参见 ArrayList
例子).
On the other hand, tryAdvance
is what hasNext/next
is from an Iterator
, but it's a single method, much easier to reason about, IMO. Related to this, is forEachRemaining
which in the default implementation delegates to tryAdvance
, but it does not have to always be like this (see ArrayList
for example).
Spliterator 也是一个更智能"的迭代器,通过其内部属性,如 DISTINCT
或 SORTED
等(在实现自己的 Spliterator
).这些标志在内部用于禁用不必要的操作;例如,请参阅此优化:
A Spliterator also is a "smarter" Iterator, via its internal properties like DISTINCT
or SORTED
, etc (which you need to provide correctly when implementing your own Spliterator
). These flags are used internally to disable unnecessary operations; see for example this optimization:
someStream().map(x -> y).count();
因为在流的情况下大小不会改变,所以可以完全跳过map
,因为我们所做的只是计数.
Because size does not change in the case of the stream, the map
can be skipped entirely, since all we do is counting.
如果需要,您可以通过以下方式围绕 Iterator 创建 Spliterator:
You can create a Spliterator around an Iterator if you need to, via:
Spliterators.spliteratorUnknownSize(yourIterator, properties)
这篇关于Java8中Iterator和Spliterator的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!