Pure Danger Tech


Learning Clojure #5: Iterator as Sequence

09 Feb 2010

Some of the first code I wrote in Clojure was calling into an existing Java library which returned something that extends Iterator.

In Clojure, everything good under the sun comes from working with everything as sequences. A Java Iterator seemed similar to a sequence but I couldn’t immediately figure out how to treat make the leap.

I used the handy find-doc function to search for something iterator related:

user=> (find-doc "iterator")
  Returns a seq on a java.util.Iterator. Note that most collections
  providing iterators implement Iterable and thus support seq directly.

In this case I was dealing with an API that just returned an Iterator, not a collection at all but it was as simple as just wrapping the Iterator return in iterator-seq:

(iterator-seq result-set)