Mantas Vidutis
Mantas Vidutis

Reputation: 16794

Convert an array of tuples into a hash-map in Clojure

I have an array of tuples, where each tuple is a 2 tuple with a key and a value. What would be the cleanest way to convert this array of tuples into a hash-map?

Upvotes: 40

Views: 15452

Answers (4)

miner49r
miner49r

Reputation: 1107

A map is a sequence of MapEntry elements. Each MapEntry is a vector of a key and value. The tuples in the question are already in the form of a MapEntry, which makes things convenient. (That's also why the into solution is a good one.)

user=> (reduce conj {} [[:a 1] [:b 2]])
{:b 2, :a 1}

Upvotes: 7

PheliX
PheliX

Reputation: 906

user=> (into {} [[:a 1] [:b 2]])
{:a 1, :b 2}

Upvotes: 57

edbond
edbond

Reputation: 3951

user=> (def a [[:a 4] [:b 6]])
user=> (apply hash-map (flatten a))
{:a 4, :b 6}

Upvotes: 3

kotarak
kotarak

Reputation: 17299

Assuming that "tupel" means "two-elememt array":

(reduce 
  (fn [m tupel] 
      (assoc m 
            (aget tupel 0) 
            (aget tupel 1))) 
  {} 
  array-of-tupels)

Upvotes: 5

Related Questions