Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swap keys and values in a map

Tags:

clojure

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?

like image 753
murtaza52 Avatar asked Mar 24 '13 06:03

murtaza52


People also ask

Can we change key in map?

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 .

How can I change HashMap value in Java?

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.


1 Answers

This is the purpose of map-invert in clojure.set:

user=> (clojure.set/map-invert {:a 2 :b 4})
{4 :b, 2 :a}
like image 122
A. Webb Avatar answered Sep 27 '22 19:09

A. Webb