且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java Streams是Iterator Design Pattern的实现吗?

更新时间:2022-12-25 12:06:37

我们可以认为对Collection的.stream()调用会创建某种迭代器吗?

Can we consider that the .stream() call on a Collection create some sort of an iterator?

是的,我们可以!但是有趣的问题是,它是一种什么样的迭代器?

Yes we can! But the interesting question is, what sort of an iterator is it?

Iterator具有许多实现变体和替代方案. (第260页)

Iterator has many implementation variants and alternatives. (p. 260)

我们可能无法将流识别为迭代器,因为(在Java中)我们习惯于看到客户端显式调用next()hasNext()的模式版本.流显然不是Iterator模式的那个版本,那么它们是什么?

We might not recognize a stream as an iterator, because (in Java) we are so used to seeing the version of the pattern where the client explicitly calls next() and hasNext(). Streams are clearly not that version of the Iterator pattern, so what are they?

谁控制迭代?一个基本的问题是确定哪一方控制迭代,迭代器或使用迭代器的客户端.当客户端控制迭代时,迭代器称为外部迭代器,而当迭代器控制迭代器时,迭代器为内部迭代器.使用外部迭代器的客户端必须推进遍历并从迭代器中显式请求下一个元素.相反,客户端将内部迭代器交给要执行的操作,然后迭代器将该操作应用于聚合中的每个元素.

Who controls the iteration? A fundamental issue is deciding which party controls the iteration, the iterator or the client that uses the iterator. When the client controls the iteration, the iterator is called an external iterator, and when the iterator controls it, the iterator is an internal iterator. Clients that use an external iterator must advance the traversal and request the next element explicitly from the iterator. In contrast, the client hands an internal iterator an operation to perform, and the iterator applies that operation to every element in the aggregate.

所以Stream仍然是迭代器,但是是内部迭代器,与IteratorEnumeration等较早的Java API相对.

So a Stream is still an iterator, but an internal iterator as opposed to the older Java APIs like Iterator and Enumeration.