Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Iterator and Stream in Scala?

Tags:

scala

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?

like image 557
ryeguy Avatar asked Oct 06 '09 20:10

ryeguy


People also ask

What is the difference between iterator and stream?

Iterators, in Java, are used in Collection Framework to retrieve elements one by one. A stream in Java is a pipeline of objects from an array or a collection data source. A sequential stream is one in which the objects are pipelined in a single stream on the same processing system.

What is an iterator in Scala?

An iterator is not a collection, but rather a way to access the elements of a collection one by one. The two basic operations on an iterator it are next and hasNext . A call to it. next() will return the next element of the iterator and advance the state of the iterator.

What is a stream in Scala?

The Stream is a lazy lists where elements are evaluated only when they are needed. This is a scala feature. Scala supports lazy computation. It increases performance of our program. Streams have the same performance characteristics as lists.

Is Scala iterator lazy?

Unlike operations directly on a concrete collection like List , operations on Iterator are lazy. A lazy operation does not immediately compute all of its results.


1 Answers

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.

like image 192
Walter Chang Avatar answered Sep 18 '22 14:09

Walter Chang