Java Streams是Iterator Design Pattern的实现吗? [英] Are Java Streams implementations of Iterator Design Pattern?

查看:58
本文介绍了Java Streams是Iterator Design Pattern的实现吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

那么,正如标题所要求的,可以将Java Streams视为Iterator模式的实现吗?

So, as the title asks, can Java Streams be considered an implementation of the Iterator pattern?

我们是否可以认为对Collection的.stream()调用会创建某种迭代器,使您可以解析该Collection的元素,而无需实际暴露Collection的表示形式? (如果我没有记错的话,迭代器模式的含义是什么)

Can we consider that the .stream() call on a Collection create some sort of an iterator which allows you to parse the elements of that Collection, without actually exposing the representation of the Collection? (Which is what the Iterator Pattern implies, if I am not mistaking)

为避免混淆,请注意,我对Java的Iterator接口不感兴趣,我只想知道Java Streams是否可以视为Iterator Design Pattern的实现,为什么?

to avoid confusion, please note that I am not interested in Java's Iterator interface, I just want to know if Java Streams can be considered an implementation of the Iterator Design Pattern, and why?

推荐答案

我们可以认为对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.

这篇关于Java Streams是Iterator Design Pattern的实现吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆