Difference between Iterator and Stream in Scala?

Scala

Scala Problem Overview


It seems that both Iterator and Stream are lazy and allow you to keep returning elements to your heart's content. What's the difference between the two?

Scala Solutions


Solution 1 - Scala

Stream memoises and Iterator does not. You can traverse the same Stream multiple times and get the same result each time. Iterator, on the other hand, can only be traversed once.

Solution 2 - Scala

They are both constructs for accessing a current element, having a yet unknown list of remaining elements (the lazy tail).

Iterator is an imperative construct which you can only traverse once.

Stream is a functional construct. In theory you can traverse it multiple times (and as others mentioned, it won't recompute the already computed parts), but in practice because Streams are either infinite or very large (that is why you use it in the first place), holding reference to the full stream doesn't make much sense (you run into Out Of Memory pretty easy).

Generally it is safer to the mind to avoid plain Streams. Alternatives are using EphemeralStream of Scalaz which auto-forgets unreferred parts using weak references, or using Iteratees (see also here) or something similiar.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionryeguyView Question on Stackoverflow
Solution 1 - ScalaWalter ChangView Answer on Stackoverflow
Solution 2 - ScalaronView Answer on Stackoverflow