Recipe: Converting an Iterator to a Stream

If you have an object that acts as a "generator" of a stream, like a scala Iterator, you can use Stream.unfold to create a stream.

def toStream[A](iter: Iterator[A]) = Stream.unfold(iter)(i=>if(i.hasNext) Some((i.next,i)) else None)

The basic idea is to treat the iterator as the "state" that must be passed to each successive fetch for a value. The only trick part is to ensure you know what the stopping criteria is and translate that stopping criteria to a None to stop the stream.

You can use this pattern when you have an object that is both the state and the generator of values. If you can generate the next element from the previous element, you can use Stream.iterate. Note that when you use Stream.iterate you can have collaborating objects that help you calculate the next element and you cannot self-terminate the stream.

Last updated