jQuery in Action, 2nd edition
The moose likes Clojure and the fly likes Clojure Maps Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Languages » Clojure
Reply Bookmark "Clojure Maps" Watch "Clojure Maps" New topic
Author

Clojure Maps

Rajith Gamage
Greenhorn

Joined: Jun 17, 2010
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

Joined: May 25, 2011
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

Joined: Feb 09, 2011
Posts: 193
    
    1

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.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Clojure Maps
 
Similar Threads
EL concatenation -> ${map[ ?+? ]}
Threads and serialization
HasMap iteration
Doubts
Unique values from a Map