Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Clojure Maps

 
Rajith Gamage
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Clojure Linux Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic