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
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())
            {
                TraversedResultMap.put(String.valueOf((String)results.get(s)),String.valueOf((String)results.get(s)));
            }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

 

TraversedResultMap.put(String.valueOf((String)results.s),String.valueOf((String)results.get(s)));

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:

 

TraversedResultMap.put(s,String.valueOf((String)results.get(s)));

LBKLBK
This is what you need in for loop.
for (String s : results.KeySet())
 {
     TraversedResultMap.put(String.valueOf(results.get(s)),String.valueOf(results.get(s)));
 }
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++)
{
   TraversedResultMap.put(listStrings.get(i),listStrings.get(i+1));


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
try
TraversedResultMap.put(s,,String.valueOf(results.get(s)));