convert between PersistentArrayMap and HashMap

2,195 views
Skip to first unread message

Makoto Hashimoto

unread,
Sep 14, 2014, 8:16:04 PM9/14/14
to clo...@googlegroups.com
I am writing clojure code calls java's method which parameters and return are HashMap.

When I call java method with clojure's Map, the following error occurred.
 
     java.lang.ClassCastException: clojure.lang.PersistentArrayMap cannot be cast to java.util.HashMap


So, I'd like to convert nested clojure.lang.PersistentArrayMap into java.util.HashMap
and nested HashMap into PersistentArrayMap.

Clojure's map is like {:a 1 :b {:c 1 :d 2} :e {:f 10 :g 11}}.

Is there the efficient way to convert type between Clojure's map and java's map ?

Thanks,
Makoto


Alex Miller

unread,
Sep 15, 2014, 10:12:47 AM9/15/14
to clo...@googlegroups.com
Well first I'd say that the Java api you're calling into isn't very good if it expects specifically java.util.HashMap. Clojure's map data structures implement java.util.Map so generally they can be passed into Java api methods that take the interface (good practice).

However, HashMap has a constructor that takes a map, so just calling:

(java.util.HashMap. {:a 1 :b {:c 1 :d 2} :e {:f 10 :g 11}})

should work. If you want to do it recursively, you can use clojure.walk/postwalk, something like:

(postwalk #(if (map? %) (java.util.HashMap. %) %) my-data)

webber

unread,
Sep 15, 2014, 5:30:51 PM9/15/14
to clo...@googlegroups.com
You are right. As you pointed out, my java interface design is not good. 
I've changed java interface into java.util.Map and I could pass Clojure's map to the java interface.
I've also tested clojure.walk/postwork. The clojure.walk library is fine !

Thanks,
Makoto


Reply all
Reply to author
Forward
0 new messages