-1

I am new to Clojure. I am trying to use java hashmap in clojure. I am passing a java hashmap to Clojure. The map is- {0=Goa, 1=Delhi, 2=Mumbai}. When I am trying to use the clojure functions on this map I am not getting the expected output. In contrast to this when I am iterating over this map it is giving the expected output.

Example
   (println(get map 0)) is giving nil




(doseq [[key value] map
      (println value)) is giving the expected output.

        Output-Goa
               Delhi
               Mumbai

Can somebody please expain me why is this happening?

Joe C
  • 15,324
  • 8
  • 38
  • 50
ditri
  • 31
  • 3
  • Please be mindful about how you tag your questions. Given your question is not about [tag:java], attracting Java experts to your question is not going to help you. – Joe C Jan 05 '19 at 19:06

3 Answers3

1

You really should google a bit to find pre-existing answers like this one: Clojure: working with a java.util.HashMap in an idiomatic Clojure fashion

You can then see a simple answer:

(def data {:a 1 :b 2 :c 3})

(def java-map (java.util.HashMap. data))
(def clj-map  (into {} java-map))

which gives us:

java-map  => <#java.util.HashMap {:b 2, :c 3, :a 1}>
clj-map   => <#clojure.lang.PersistentArrayMap {:b 2, :c 3, :a 1}>

and looping:

  (doseq [[k v] clj-map]
    (println (format "key=%s  val=%s" k v)) )

with result:

key=:b  val=2
key=:c  val=3
key=:a  val=1
Alan Thompson
  • 29,276
  • 6
  • 41
  • 48
0

I think your problem is that your map is named "map" which is also a Clojure function. Try it like this:

(def my-map {0 "Goa" 1 "Delhi" 2 "Mumbai"})

Which then will work like this:

(println (get my-map 0))

Note that it still returns nil, since there is nothing else after the (println) form but it does print the value of the 0 in the map, which is "Goa".

jwh20
  • 646
  • 1
  • 5
  • 15
  • While it's true that you shouldn't use `map` as the name of your map, if you try it on the REPL you should just get a warning like `WARNING: map already refers to: #'clojure.core/map in namespace: user, being replaced by: #'user/map`. It would cause bizarre behavior if you then naively try to use the normal Clojure `map` function, but wouldn't cause the specific issue described here. – Ben Schmidt Jan 05 '19 at 19:31
  • @BenSchmidt Thanks for the clarification. It's not totally clear to me where his "map" came from since that part of the code is missing from the original question. – jwh20 Jan 05 '19 at 19:48
0
(def input-map {0 "Goa" 1 "Delhi" 2 "Mumbai"})

(map (fn[[k v]] (print "key " k " value " k)) input-map) 

[[k v]] for function let you access key and value for each entry

(map print input-map)

here map entry will be passed as parameter to print

Narendra Pinnaka
  • 205
  • 1
  • 2
  • 11