function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Gopikrishna DasariGopikrishna Dasari 

Can anyone help me in this?

I have a map like this
 map<Integer,string> mapof = new map<integer,string> {1=>'Ramu',2=>'suresh'3='ramesh' 4=>'Ramu'};

I want to revrse this map 
 map<string,Integer> mapof1 = new map<integer,string> {'Ramu'=>1,'suresh'=>2,'ramesh' =3,'Ramu'=>4};

how can we do this?
 
Best Answer chosen by Gopikrishna Dasari
SwethaSwetha (Salesforce Developers) 
HI Gopi,
To reverse the map, you can use a for loop to iterate over the original map and add the values to a new map with the keys and values swapped.
map<Integer, String> mapof = new map<Integer, String> {1=>'Ramu', 2=>'suresh', 3=>'ramesh', 4=>'Ramu'};
map<String, Integer> mapof1 = new map<String, Integer>();

for (Integer key : mapof.keySet()) {
    String value = mapof.get(key);
    mapof1.put(value, key);
}

System.debug(mapof1);

Note that if the original map contains duplicate values, the new map will only contain the last key-value pair with that value, since maps cannot have duplicate keys.

Related:
https://stackoverflow.com/questions/4436999/how-to-swap-keys-and-values-in-a-map-elegantly
https://shreysharma.com/map-initialization-methods/
https://salesforce.stackexchange.com/questions/38767/iterating-over-a-map-apex

If this information helps, please mark the answer as best. Thank you

All Answers

SwethaSwetha (Salesforce Developers) 
HI Gopi,
To reverse the map, you can use a for loop to iterate over the original map and add the values to a new map with the keys and values swapped.
map<Integer, String> mapof = new map<Integer, String> {1=>'Ramu', 2=>'suresh', 3=>'ramesh', 4=>'Ramu'};
map<String, Integer> mapof1 = new map<String, Integer>();

for (Integer key : mapof.keySet()) {
    String value = mapof.get(key);
    mapof1.put(value, key);
}

System.debug(mapof1);

Note that if the original map contains duplicate values, the new map will only contain the last key-value pair with that value, since maps cannot have duplicate keys.

Related:
https://stackoverflow.com/questions/4436999/how-to-swap-keys-and-values-in-a-map-elegantly
https://shreysharma.com/map-initialization-methods/
https://salesforce.stackexchange.com/questions/38767/iterating-over-a-map-apex

If this information helps, please mark the answer as best. Thank you
This was selected as the best answer
Gopikrishna DasariGopikrishna Dasari
Hi Swetha,

Thanks for your answer.