+ Start a Discussion
Micky MMicky M 

Map

Hi all does anyone know how i can create a map which has an id then a list of opportunities associated with it? 

 

something like 

 

map<string, List<Opportunity>> oppMap = newmap<string, List<Opportunity>>([select o.Sugar_ID__c, o.id from Opportunitywhere AccountId = null]);

 

where the Sugar_ID__c is the key and the opp id is the value, i know what i need to do just not sure how to do it. 

 

Thanks All

Best Answer chosen by Admin (Salesforce Developers) 
craigmhcraigmh

You could query for all Opportunity records where AccountId is null, and put that in a single list. Then declare the Map:

 

Map<Id, List<Opportunity>> oppMapp = new Map<Id, List<Opportunity>>();

 

Loop through the opportunities. First step is to see if the key exists. If it doesn't, add it.

 

Then add the Opportunity record to the collection of the corresponding Map value.

 

for(Opportunity o: opps) {
	if(!oppMap.containsKey(o.AccountId)) { oppMap.add(o.AccountId, new List<Opportunity>()); }
	oppMap.get(o.AccountId).add(o);
}

 

(exact syntax may vary)

All Answers

craigmhcraigmh

You could query for all Opportunity records where AccountId is null, and put that in a single list. Then declare the Map:

 

Map<Id, List<Opportunity>> oppMapp = new Map<Id, List<Opportunity>>();

 

Loop through the opportunities. First step is to see if the key exists. If it doesn't, add it.

 

Then add the Opportunity record to the collection of the corresponding Map value.

 

for(Opportunity o: opps) {
	if(!oppMap.containsKey(o.AccountId)) { oppMap.add(o.AccountId, new List<Opportunity>()); }
	oppMap.get(o.AccountId).add(o);
}

 

(exact syntax may vary)

This was selected as the best answer
Micky MMicky M

Thats it sir, thats pretty much done what i need to thanks for your help!