I have a requirement, where I have to fecth record and put it in a Map. I have a custom Object My_Object__c and it has 2 fields : child_Name__c and Parent_Name__c.

What I did, I query from the My_Object__c and put the record in Map<String, My_Object__c> dataMap.

Now I want to store data in a Map. Map<String, Set<String>> secondMap// 1st String : parent_Name__c and 2nd String : child_Name__c. where 1st string is the unique value.

Table will look like below.

child_Name__c Parent_Name__c A AB B AB C AB K BC F BC

dataMap :[AB : {A,B,C}, BC : {k,F}]

This is what I did :

**Class **

dateMap = new Map<String, My_Object__c >();
for(My_Object__c obj : [select Id,child_Name__c,Parent_Name__c
                         from My_Object__c 
                        ]) {
    dateMap.put(obj.child_Name__c, obj );   

By using this dataMap, how I will create the Map<String, Set<String>> secondMap


You may not require to use first map i.e datamap. You can create 2nd map directly as follows:

Map<String, Set<String>> secondMap = new Map<String, Set<String>>(); 
for(My_Object__c obj : [select Id,child_Name__c,Parent_Name__c from My_Object__c]) {
         secondMap.put(obj.Parent_Name__c, new Set<String>{obj.child_Name__c});

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.