简体   繁体   中英

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?

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

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

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

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}
user=> (def a [[:a 4] [:b 6]])
user=> (apply hash-map (flatten a))
{:a 4, :b 6}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM