+ Start a Discussion
Ashok Kumar NayakAshok Kumar Nayak 

How Can I convert a Map of (Key1=Value1,Key2=Value2) into a Map of (Value1=Valu2) in Apex ?

Here's what I'm trying :-

I've Map<String, Object> results = {Id=10001,Value=7777}, I want a map with {10001=7777} type.

This is what I attempted :-

Map<String,String> TraversedResultMap = new Map<String,String>();
            for (String s : results.KeySet())
            }system.debug('###TRAVERSED RESULT'+TraversedResultMap);
But I'm getting o/p as : {10001=10001,7777=7777}
Any Help would be appreciated

Deepak Maheshwari 7Deepak Maheshwari 7

Hi Ashok,


Please try



Ashok Kumar NayakAshok Kumar Nayak

Hi Deepak,

'result' is an Instance of another Map<String,Object>, so if I try to do result.s then I'm getting the below error :-

Initial term of field expression must be a concrete SObject: Map<String,Object>

Deepak Maheshwari 7Deepak Maheshwari 7

Please try below:



This is what you need in for loop.
for (String s : results.KeySet())
Let me know if this works for you.
Shiva RajendranShiva Rajendran

Hi Ashok,
Use the below code
Map<String,String> TraversedResultMap = new Map<String,String>();
Set<String> allKeySets = results.KeySet(); // returns a set of key value

List<String> listStrings = new List<String>(setStrings); // convert the set to a list for iterating
for(integer i=0;i<listStrings.size() -1 ;i++)

This code may cause issue if the size of the list is one. 

I hope this code will solve your problem.
Thanks and Regards,
Shiva RV

Vivek PawarVivek Pawar