Read Clojure Map Values 2/2
Here is another chapter of the series.
For those who missed the previous chapter:
-
Create Maps Overview of: hash-map, array-map, zipmap, sorted-map and sorted-map-by
-
Create Maps Overview of: bean, frequencies, group-by, clojure.set/index
We are going to continue to explore how to read clojure map.
This time we are going to talk about keys
, vals
and select-keys
.
keys and vals
keys
and vals
are extremely similar.
keys
return a sequence of all the keys of a map.
vals
return a sequence of all the values of a map.
Using keys
and vals
you need to remember that there is no order inside a simple hash-map
so you cannot make any assumption about the final sequence.
However if you use sorted-map
or also array-map
you can assume that the order of the keys and the order of the values will be maintained.
Something pretty obvious but useful to remember the use of keys
and vals
is the following snippet.
select-keys
This function is useful to shrink map.
Given a map and a sequence of keys return the map shrinked to only the keys in the sequence.
As you can see if a key is not present in the original map the returning map won’t contains such key.
What we need to note here is that select-keys
takes only two arguments, the starting map and a vector of keys.
You may try to pass the keys to select as a simple arguments but that will result in a pretty cryptic error.
end
This was the last chapter about reading clojure map.
Next time we are going to explore deeply how to modify a map adding and removing entries.
As always stay tunned, and for any question don’t esitate to write me.
Next Chapter: Map transformation in clojure 1/2 assoc, dissoc, merge