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")
