Is there a function to swap the key and value of a given map. So given a map, I want the keys to become values, and values the keys.
(swap {:a 2 b 4}) => {2 :a 4 :b}
One way to do it is
(zipmap (vals my-map) (keys my-map))
However wondering if clojure provides a utility fn for this?
No,You can not rename the key of HashMap once added. Very first you have to delete or remove that key and then you can insert with new key with value . Because in HashMap internal implementation the HashMap key modifier is final .
The replace(K key, V value) method of Map interface, implemented by HashMap class is used to replace the value of the specified key only if the key is previously mapped with some value. Parameters: This method accepts two parameters: key: which is the key of the element whose value has to be replaced.
This is the purpose of map-invert
in clojure.set
:
user=> (clojure.set/map-invert {:a 2 :b 4})
{4 :b, 2 :a}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With