Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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

share|improve this question

1 Answer 1

up vote 3 down vote accepted

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]) {
    if(!secondMap.containsKey(obj.parent_Name__c)){
         secondMap.put(obj.Parent_Name__c, new Set<String>{obj.child_Name__c});

    }else{
         secondMap.get(obj.Parent_Name__c).add(obj.child_Name__c);
    }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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