4
votes

Clojure beginner here..

If I have a set of maps, such as

 (def kids #{{:name "Noah" :age 5}
     {:name "George":age 3}
     {:name "Reagan" :age 1.5}})  

I know I can get names like this

  (map :name kids)

1) How do I select a specific map? For example I want to get back the map where name="Reagan".

 {:name "Reagan" :age 1.5}

Can this be done using a filter?

2) How about returning the name where age = 3?

2

2 Answers

8
votes

Yes, you can do it with filter:

(filter #(= (:name %) "Reagan") kids)

(filter #(= (:age %) 3) kids)
6
votes

There's clojure.set/select:

(clojure.set/select set-of-maps #(-> % :age (= 3)))

And similarly with name and "Reagan". The return value in this case will be a set.

You could also use filter without any special preparations, since filter calls seq on its collection argument (edit: as already described by ffriend while I was typing this):

(filter #(-> % :age (= 3))) set-of-maps)

Here the return value will be a lazy seq.

If you know there will only be one item satisfying your predicate in the set, some will be more efficient (as it will not process any additional elements after finding the match):

(some #(if (-> % :age (= 3)) %) set-of-maps)

The return value here will be the matching element.