Into hashmap from list


#1

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?


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

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

#3

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


#4

there is mapv, filterv etc. to return vectors.


#5

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


#6

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


#7

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


#8

You might look into transducers as well.

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