问题描述
我无法理解接口,特别是与和接口。我的问题是我根本无法理解 Spliterator
和收集器
接口,因此 Stream
界面对我来说仍然有些模糊。
I am having trouble understanding the Stream
interface in Java 8, especially where it has to do with the Spliterator
and Collector
interfaces. My problem is that I simply can't understand yet the Spliterator
and the Collector
interfaces, and as a result the Stream
interface is still somewhat obscure to me.
Spliterator究竟是什么
和收藏家
,我该如何使用它们?如果我愿意写自己的 Spliterator
或收藏家
(可能还有我自己的 Stream
在那个过程中),我应该做什么而不是做什么?
What exactly is a Spliterator
and a Collector
, and how can I use them? If I am willing to write my own Spliterator
or Collector
(and probably my own Stream
in that process), what should I do and not do?
我读了一些分散在网络上的例子,但由于这里的一切都是新的并且如有变更,示例和教程仍然非常稀少。
I read some examples scattered around the web, but since everything here is stil new and subject to changes, examples and tutorials are still very sparse.
推荐答案
您几乎肯定不会处理 Spliterator
作为用户;只有在你自己编写 Collection
类型并且也打算优化它们的并行化操作时才应该这样做。
You should almost certainly never have to deal with Spliterator
as a user; it should only be necessary if you're writing Collection
types yourself and also intending to optimize parallelized operations on them.
对于它的价值, Spliterator
是一种以某种方式操作集合元素的方式很容易将部分收藏拆分,例如因为你是并行化的,并且希望一个线程可以在集合的一个部分上工作,一个线程可以在另一个部分上工作,等等。
For what it's worth, a Spliterator
is a way of operating over the elements of a collection in a way that it's easy to split off part of the collection, e.g. because you're parallelizing and want one thread to work on one part of the collection, one thread to work on another part, etc.
你本质上永远不应该保存值类型流
到一个变量。 Stream
有点像 Iterator
,因为它是一个一次性使用的对象,你几乎总是在一个流畅的链中使用,如在Javadoc示例中:
You should essentially never be saving values of type Stream
to a variable, either. Stream
is sort of like an Iterator
, in that it's a one-time-use object that you'll almost always use in a fluent chain, as in the Javadoc example:
int sum = widgets.stream()
.filter(w -> w.getColor() == RED)
.mapToInt(w -> w.getWeight())
.sum();
收藏家
是最普遍的,抽象的可能la map / reduce的reduce操作的版本;特别是,它需要支持并行化和完成步骤。 收集器
的示例包括:
Collector
is the most generalized, abstract possible version of a "reduce" operation a la map/reduce; in particular, it needs to support parallelization and finalization steps. Examples of Collector
s include:
- 求和,例如:
Collectors.reducing(0,(x,y) - > x + y)
- StringBuilder追加,例如
Collector.of(StringBuilder :: new,StringBuilder :: append,StringBuilder :: append,StringBuilder :: toString)
- summing, e.g.
Collectors.reducing(0, (x, y) -> x + y)
- StringBuilder appending, e.g.
Collector.of(StringBuilder::new, StringBuilder::append, StringBuilder::append, StringBuilder::toString)
这篇关于了解Java 8中的Spliterator,Collector和Stream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!