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
shweta kumari 25shweta kumari 25 

List Inside Map issue

I have a Map defined as follows
Map<ID,List<Opportunity>> accMap = new Map<ID,List>Opportunity>>();

My requirement is I need to fill the List<Oppotunity> defined inside the map with data from the Opportunity object and accountIDs for the Map.

like select [ID,Name,Amount from opportunity to be filled inside the list and from opportunity we get the accountID and this will be in Map like
accMap.put(o.accountID) some thing like this.

I hope I am clear.

please let me code if possible how to achieve this scenario.

thanks
shweta


 
Best Answer chosen by shweta kumari 25
Steven NsubugaSteven Nsubuga
    Map<Id, List<Opportunity>> accMap = new Map<Id, List<Opportunity>>();	
	List<Opportunity> opps = [SELECT Id, Name, AccountId, Amount from opportunity];
    for (Opportunity opp : opps) {
		List<Opportunity> opportunities = accMap.get(opp.AccountId);
        if (opportunities == null) {
			opportunities = new List<Opportunity>();
		}
		opportunities.add(opp);
		
		accMap.put(opp.AccountId, Opportunities);
    }

 

All Answers

Steven NsubugaSteven Nsubuga
    Map<Id, List<Opportunity>> accMap = new Map<Id, List<Opportunity>>();	
	List<Opportunity> opps = [SELECT Id, Name, AccountId, Amount from opportunity];
    for (Opportunity opp : opps) {
		List<Opportunity> opportunities = accMap.get(opp.AccountId);
        if (opportunities == null) {
			opportunities = new List<Opportunity>();
		}
		opportunities.add(opp);
		
		accMap.put(opp.AccountId, Opportunities);
    }

 
This was selected as the best answer
mritzimritzi
Map<Id,List<Opportunity>> accMap = new Map<Id,List>Opportunity>>();
for(Opportunity opp: [Select Id, Name, Amount, AccountId From Opportunity LIMIT 50000]){
	//this will execute only when accountId is not yet added in the map
	if(!accMap.containsKey(opp.AccountId))
		accMap.put(opp.AccountId, new List<Opportunity>());
	//add the opportunity in the list of opportunities associated with accountId
	accMap.get(opp.AccountId).add(opp);
}

Please mark this as BEST ANSWER, if this helps solve your problem
 
shweta kumari 25shweta kumari 25
Thanks Steven and  mritzi