liveBook · Manning

Iterator-seq

As explained in Clojure: The Essential Reference

iterator-seq is a Clojure function that creates a sequence by traversing a java.util.Iterator.

iterator-seq creates a Clojure sequence by traversing an existing java.util.Iterator. It is useful when an iterator is the only available object, such as a function’s return value, rather than a collection with an iterator() method. section 9.3.8

Its contract is small but includes important edge behavior:

  • Accepts an object implementing java.util.Iterator. section 9.3.8
  • Returns a sequence produced by iterating that object, or nil when the iterator comes from an empty collection. section 9.3.8
  • Throws NullPointerException when given nil. section 9.3.8
  • Produces a cached sequence: consumed items remain in the sequence, and later iterator mutations or remove operations are not visible through it. section 9.3.8

Wrapping a Java iterator

(def an-iterator (.iterator [1 2 3])) (iterator-seq an-iterator) ;; (1 2 3) A Java 8 stream can be adapted similarly: split a string into a stream, obtain its iterator, then call iterator-seq. (->> "Clojure is the best language" (.splitAsStream #"\\s+") .iterator iterator-seq) ;; ("Clojure" "is" "the" "best" "language")

How Clojure: The Essential Reference covers it

How deep it goes
Defines inputs, outputs, exceptions, emptiness, caching, and mutation visibility, but does not descend into implementation internals.
Examples
Uses a vector iterator and a Java 8 string stream converted through .iterator.
What it assumes
Assumes familiarity with Clojure sequences and Java Iterator objects while defining the required interface contract.
What you can do after
Apply it via Clojure to consume Java iterators as sequences and compose them with sequence operations.
How it connects
Connects Java Iterator, Java Stream, Clojure sequences, seq, and enumeration-seq.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.