문제

If I have an array map like this:

{"red" "blue"}

How can I turn this into an array like this:

["red" "blue"]
도움이 되었습니까?

해결책 5

One and a very quick way:

(flatten (vec {"red" "blue"}))

=> ("red" "blue")

If you really want an array:

 (into-array (flatten (vec {"red" "blue"})))

 => #<String[] [Ljava.lang.String;@4dc2753>

Keep in mind that in Clojure, ["red" "blue"] is a vector, not an array. And { } means map. Clojure first creates an array map but later, it promotes it to hash map when it is necessary.

다른 팁

Maps hold an unordered set of MapEntry objects, which act like vectors, so just calling first on the map will convert it to a sequence, then grab the first map entry:

(first {"red" "blue"})
; ["red" "blue"]
(vec (mapcat seq {"red" "blue"}))
; ["red" "blue"]
user> (vec (apply concat {:a 0 :b 1 :c 2 :d 3}))
[:c 2 :b 1 :d 3 :a 0]

This is similar to Thumbnail's solution, but calling seq is redundant.

Also assumed you mean vector and not array. If having the output just be linear suffices then the call to vec can be eliminated as well.

The problem with the flatten option is if there is internal structure of any sort in the map:

user> (flatten (seq {:a 0 :b 1 :c [2 3]}))
(:c 2 3 :b 1 :a 0)
user> (apply concat {:a 0 :b 1 :c [2 3]})
(:c [2 3] :b 1 :a 0)

If you want to handle empty maps as empty vectors and maps with multiple pairs as a vector of [key val key val...] then you can use reduce into [] or reduce-kv conj [].

so.core=> (reduce into [] {"red" "blue"})
["red" "blue"]
so.core=> (reduce into [] {:a 0 :b 1 :c 2 :d 3})
[:c 2 :b 1 :d 3 :a 0]
so.core=> (reduce into [] {})
[]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top