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
Mahesh NirmalMahesh Nirmal 

Adding Values to Map.

I have two List

List<String> filteredValues = New List<String>();
List<Contract__c> valuesForfilteredValues = something query.

And I have to add them to a map

Map<String, String> detailsMap;

How should I do that.

Scenario.
Let's Say-

The first list has values (Name, City, State);
Second List has values (TestName, Mumbai, MH);
I have to perform dynamically as-

detailsMap.put(Name , TestName);
detailsMap.put(City , Mumbai);
detailsMap.put(State , MH);

Please suggest a way to do this.

Best Answer chosen by Mahesh Nirmal
ravi soniravi soni
Hy Mahesh,
try this 
List<String> filteredValues = New List<String>{'Name','city__c','State__c'};
List<Contact> lstContact = [SELECT Id,Name,city__c,State__c FROM Contact Where State__c != null limit 1];

map<String,String> MapOfRecord = new Map<String,string>();

for(string Key : filteredValues){
    for(Contact con : lstContact){

        MapOfRecord.put(key,String.valueOf(con.get(key)));        
    }
}
system.debug('MapOfRecord=====> ' + MapOfRecord);


/*Output : MapOfRecord=====> {Name=Rose Gonzalez, State__c=Madhya Pradesh, city__c=Indor}*/

Let me know, if it's helps you and do best mark.
Thank You

All Answers

ANUTEJANUTEJ (Salesforce Developers) 
Hi Mahesh,

If the sceanrio is that the name city and state keys are repeated then you won't be able to use a map as the keys in the map needs to be unique if that is the case then I would suggest you to have a key that is unique like Mumbai and then the value would be list of parameters.

For example:
Map<String, List<String>> detailsMap = new Map<String, List<String>>();
List<String> ls1 = new List<String>();
ls1.add('Test Name');
ls1.add('Mumbai');
ls1.add('MH');
detailsMap.put('Mumbai',ls1);

Please note the above is an example and you will have to modify it as per your use case.

Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.  

Thanks.
ravi soniravi soni
Hy Mahesh,
try this 
List<String> filteredValues = New List<String>{'Name','city__c','State__c'};
List<Contact> lstContact = [SELECT Id,Name,city__c,State__c FROM Contact Where State__c != null limit 1];

map<String,String> MapOfRecord = new Map<String,string>();

for(string Key : filteredValues){
    for(Contact con : lstContact){

        MapOfRecord.put(key,String.valueOf(con.get(key)));        
    }
}
system.debug('MapOfRecord=====> ' + MapOfRecord);


/*Output : MapOfRecord=====> {Name=Rose Gonzalez, State__c=Madhya Pradesh, city__c=Indor}*/

Let me know, if it's helps you and do best mark.
Thank You
This was selected as the best answer