Java8中Iterator和Spliterator之间的区别
我在研究 Parallelism
时发现了 Spliterator
的主要优势。
I came to know while studying that Parallelism
is a main advantage of Spliterator
.
这可能是一个基本问题,但任何人都可以向我解释 Iterator
和 Spliterator $ c之间的主要区别$ c>并给出一些例子?
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's sort of has the same functionality like 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.
迭代器
总是一个未知的大小,你只能通过 hasNext /下一; Spliterator
可以提供大小(从而在内部改进其他操作);要么通过 getExactSizeIfKnown
,要么通过估计大小
。
An Iterator
has always 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
,但这是一种方法,更容易推理IMO。与此相关的是 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 be like this always. (see ArrayList
for example)
Spliterator也是一个更聪明的迭代器,通过它的内部属性如 DISTINCT 或 SORTED
等(在实现自己的 Spliterator时需要正确提供 code>)。这些标志在内部用于禁用不必要的操作,也称为优化,例如:例如:
A Spliterator is also a "smarter" Iterator, via it's 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, also called optimizations, like this one for example:
someStream().map(x -> y).count();
因为在流的情况下大小不会改变,所以地图
可以完全跳过,因为我们所做的只是计算。
Because size does not change in 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 would need to, via:
Spliterators.spliteratorUnknownSize(yourIterator, properties)