Into hashmap from list

So into with hashmap and vector basically works like this:

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

But with lists it doesn’t work like that:

(into {} '((:a 1) (:b 2)))
; => ClassCastException class clojure.lang.Keyword cannot be cast to class java.util.Map$Entry (clojure.lang.Keyword is in unnamed module of loader 'app'; java.util.Map$Entry is in module java.base of loader 'bootstrap')  clojure.lang.ATransientMap.conj (ATransientMap.java:44)

Which isn’t nice, since now I can’t do something like this:

(->> [[:a 1 true]
      [:b 2 false]]

     (filter last)
     (map drop-last)
     (into {}))

So what do I do then? "( . _ .)
How would you do it?

(->> [[:a 1 true]
      [:b 2 false]]

     (filter last)
     (map drop-last) 
     flatten 
     (apply hash-map))

Though (filter last) doesn’t make much sense, first does the same thing

there is mapv, filterv etc. to return vectors.

3 Likes

Thank you very much, didn’t even know there was such a thing

Is there any reasoning behind treating vector tuple as MapEntry, but not list?

1 Like

map entries are a positional 2-tuple (indexed lookup). You get that with vectors, but not with lists which are only traversed sequentially.

5 Likes

You might look into transducers as well.

(into {}
      (map vec)
      '((:a 1) (:b 2)))
=> {:a 1, :b 2}
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.