8

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?

1
  • I just wanted a Clojure-native data type, so that I could work with it more easily with the repl. I see that vector is different, so I'll remove it. Commented Mar 11, 2016 at 14:58

2 Answers 2

16

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.

Sign up to request clarification or add additional context in comments.

1 Comment

In general this is true, but pop won't in general operate on the result of seq. Pop will operate on lists, though.
1

@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.

1 Comment

Props for feeding my ego! ;-p

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.