1

When I apply doseq with transient map to java.util.HashMap, I can always acquire only 8 entries. How can I acquire all the entries?

user=> (def tmp-hash (doto (new java.util.HashMap) (.put "a" 1) (.put "b" 2) (.put "c" 3) (.put "d" 4) (.put "e" 5) (.put "f" 6) (.put "g" 7) (.put "h" 8) (.put "i" 9) (.put "j" 10))
user=> (let [t (transient {})] (doseq [[k v] tmp-hash] (assoc! t k v)) (persistent! t))
{"a" 1, "b" 2, "c" 3, "d" 4, "e" 5, "f" 6, "g" 7, "h" 8}
yuji
  • 123
  • 6

1 Answers1

2

The issue is that when ArrayMap's 8-element threshold is exceeded, a new HashMap is created - which is returned as the return value of assoc!, which you are discarding in your code.

Instead of using the same object reference after assoc!, you should use the return value of assoc! to work with the transient structure:

(persistent! (reduce (fn [acc [k v]]
                       (assoc! acc k v))
                     (transient {}) tmp-hash))
Aleph Aleph
  • 5,215
  • 2
  • 13
  • 28