Search code examples
javaclojureseqsesame

How do turn a java Iterator-like object into a clojure sequence


I'm using the Sesame library to run SPARQL queries over an in-memory triple store.

I am using Clojure to achieve this.

A query result is a custom Iterator-like [1] object, so the clojure seq does not work on it out of the box.

What is the most elegant way to turn a custom java Iterator like object into a clojure sequence?

The most obvious and dumb idea that has come to my mind is to loop over it and build up a clojure vector, but I'm sure there is more elegant approach to this problem.

[1] http://www.openrdf.org/doc/sesame2/api/info/aduna/iteration/Iteration.html


Solution

  • The tested version:

    (defn iteration->seq [iteration]
     (seq
      (reify java.lang.Iterable 
          (iterator [this] 
             (reify java.util.Iterator
               (hasNext [this] (.hasNext iteration))
               (next [this] (.next iteration))
               (remove [this] (.remove iteration)))))))