Why Sequence instead of Iterator?

Some sequences may be iterated only once, and other multiple times. For example, when you create a sequence like Sequence { createIterator() } it can be iterated multiple times.
Most sequence operations, like map, filter etc, preserve this property. We decided not to expose this property in the sequence type hierarchy, as it would complicate sequence operations significantly.

This is quite not correct: sequences are not wrappers around iterator, but rather a source of (a factory of) iterators.

I’ll try to explain this in more detail.
Iterator is a stateful object since it keeps the state of iteration. While it can be iterated only once, nothing protects you from possibly applying several operations on the same iterator instance. It would go unnoticed until you’ll get incorrect results.

On the other hand Sequence is stateless: each time you begin iteration, it creates a new fresh iterator. And if the sequence doesn’t support iterating multiple times (like those sequences that were obtained by wrapping an existing iterator), it just won’t allow you to get an iterator second time.

So we believe that the sequence is better than the iterator, because it provides more clear abstraction. The same reasoning applies to java 8 streams.

2 Likes