3

What is the best way to get an unknown key from a Clojure map? I tried this -

(key {:a "test"})

which throws this -

ClassCastException clojure.lang.PersistenArrayMap cannot be cast to java.util.Map$Entry

Looking at the source code, this makes sense-

(defn key
  "Returns the key of the map entry."
  {:added "1.0" :static true}
  [^java.util.Map$Entry e]
  (. e (getKey)))

I also tried this-

(key (java.util.Map$Entry. {:a "test"}))

Which throws this-

CompilerException java.lang.IllegalArgumentException: No matching ctor found for interface java.util.Map$Entry

I understand that I can call keys and then pull said key from the KeySeq, but I was curious if there is a simple way to do this with one function call.

This is a related question in terms of interop. Thanks for the input.

Community
  • 1
  • 1
nrako
  • 2,952
  • 17
  • 30
  • If your map only contains one pair, then a vector of two elements might work better: `[:a "test"]` – DaoWen Jun 07 '16 at 17:56
  • That's helpful. I am checking each key value of an incoming hash against an existing hash to see if the key already exists, so it might be simpler to work with a vector on the incoming. Thanks for the note. – nrako Jun 07 '16 at 18:07

2 Answers2

3

(key (first {:a "test"})) will get you the key of the first entry in the map, is that what you are trying to do?

Timothy Pratley
  • 10,586
  • 3
  • 34
  • 63
  • Yes, I suppose that it is. I guess I am surprised that `key` requires a Java object. Thanks for the input. – nrako Jun 07 '16 at 17:56
  • @nrako Everything in Clojure is either a Java primitive or a Java object. The point is that `key` takes a map *entry*, not a map. – Sam Estep Jun 07 '16 at 18:44
1

You can use key or val to extract the key and value parts of a single MapEntry. For your question, it might be easier to use the keys function (note the plural) to get all of the keys from the map as a sequence:

(keys {:a "test"} )
;=> (:a)

(keys {:a "test" :b "again"} )
;=> (:a :b)

; please remember that the keys do not have to be keywords
(keys {1 11 2 22} )
;=> (1 2)
Alan Thompson
  • 29,276
  • 6
  • 41
  • 48