# Clojure Maps

Rajith Gamage
Greenhorn
Posts: 19
How can I get all values in Map?

suppose I have map like this.
({:a 1,:b 2}{:a 3,:b 6})

So I want to get the values of key 'a' . How can I get that ?

Huahai Yang
Greenhorn
Posts: 10
What you have is not a map, it is a two-maps-inside-a-list.

For a map m, , you can get all the values by using vals function: gives you (1 2). If you want only the value of the key :a, there are 3 ways: either , or , or .

Rajith Gamage wrote:How can I get all values in Map?

suppose I have map like this.
({:a 1,:b 2}{:a 3,:b 6})

So I want to get the values of key 'a' . How can I get that ?

Sean Corfield
Ranch Hand
Posts: 305
11
Rajith Gamage wrote:suppose I have map like this.
({:a 1,:b 2}{:a 3,:b 6})

Assuming you actually have that data structure - which is a list with two maps in it:

(def data '({:a 1,:b 2}{:a 3,:b 6}))

You can pull out the values for the key :a like this: (map :a data)

Why does this work? Keywords (like :a) acts as functions that can take a map as an argument and look themselves up in it. (map :a data) will apply the keyword to each map in the list, returning a sequence containing the corresponding values.

You could also write: (map #(:a %) data) using the read syntax for an anonymous function (% represents the single argument).

Or: (map (fn [m] (:a m)) data) which is probably a little easier to read if you're not used to Clojure syntax.