jpaugh
jpaugh

Reputation: 7035

Convert a Java array into a Clojure list or sequence?

How do I convert a Java array into a Clojure sequence data structure, such as a list, or other sequence?

This question shows how to do the inverse; The Clojure docs show how to create, mutate, and read arrays; but is there a built-in way to convert them to lists, or some other Clojure-native sequence?

Upvotes: 8

Views: 3576

Answers (2)

Mars
Mars

Reputation: 8854

@jpaugh is right: Usually a seq is all that you need. Many clojure collection functions work on many different structures, including seqs. If you need other collection types, though, you can often use into:

(def java-array (long-array (range 3)))
(into () java-array) ;=> (2 1 0)
(into [] java-array) ;=> [0 1 2]

Note that using into to create a list reverses the input order.

One can often use Java arrays as if they were Clojure collections. I recommend just pretending that an array is a collection in some test code at a REPL, and see what happens. Usually it works. For example:

(nth java-array 1) ;=> 1

@jpaugh's answer provides another illustration.

Upvotes: 1

jpaugh
jpaugh

Reputation: 7035

Yes, there is a way to convert an array to a list! The code (seq java-array-here) will convert the array into an ArraySeq, which implements ISeq, and thus can be treated like any other Clojure sequence.

Upvotes: 16

Related Questions