Win a copy of Real-World Software Development: A Project-Driven Guide to Fundamentals in Java this week in the Agile and Other Processes forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Bear Bibeault
  • Liutauras Vilda
  • Devaka Cooray
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Henry Wong
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • Tim Holloway
Bartenders:
  • salvin francis
  • Frits Walraven
  • Piet Souris

Clojure Maps

 
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 ?
 
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 ?

 
Rancher
Posts: 352
21
Mac OS X Monad Clojure Linux
  • 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.
 
Stinging nettles are edible. But I really want to see you try to eat this tiny ad:
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!